How to Define custom types & verify correct value at compile time?

440 Views Asked by At

I want to define new type in rust. Let's say for eg Date, which should follow dd/mm/yy format & value suppiled should be verified at compile time only. In gen, I want to define new types & add restriction to possible values.Just like i32 & other primitive types have restriction which is checked at compile time.

1

There are 1 best solutions below

5
jthulhu On

I think the most idiomatic way of doing this would be to write run time checks in a const fn, so that it can actually be called at compile time. Maybe something like that (I kept the checks very simple, but it could do more):

struct Date {
  day: u8,
  month: u8,
  year: u16,
}

impl Date {
  const fn new(day: u8, month: u8, year: u16) -> Self {
    assert!(day <= 31 && day >= 1);
    assert!(month <= 12 && month >= 1);
    Self { day, month, year }
  }
}

const TODAY: Date = Date::new(25, 06, 2022); // Compiles fine
const IN_A_WEEK: Date = Date::new(32, 06, 2022); // Compile time error

fn do_something() {
  Date::new(32, 06, 2022); // Run time error
}

See it on the playground.