Generic type level integer inequalities?

Is there a way at compile-time to ensure non-zero Strings or collections?

For instance, I know I can enforce a precise length with:


struct Me {
  name: [char;13]
}

But could I do something like this?:

struct Me<T: GREATER_THAN<1>> {
  name: [char;T]
}

This would save from a lot of runtime checks on string length (e.g. in a new or build validator)

I mean... if I could I'd use hypothetical higher-kinded types like this:

struct Me {
  name: NonEmpty<String>, // compile error if you write "".into()
  friends: NonEmpty<Vec<String>>
}

This looks kind related...: GitHub - Boddlnagg/tylar: Type-Level Arithmetic in Rust

I'm not aware of any library that provides compile-time checked non empty Strings. There is non-empty-string but that's run-time. You'd need to make something yourself with typenum.

You can not express that in types, but you can use static_assert.

It's written like const { assert!(ā€¦); } in Rust.

So something like this would work:

struct Me<const SIZE: usize> {
  name: [char; SIZE]
}
fn process_non_empty<const SIZE: usize>(me: Me<SIZE>) {
  const { assert!(SIZE > 0); }
  ā€¦
}

This may or may not be enough for you.

5 Likes