eee
February 13, 2025, 7:02pm
1
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
scimas
February 13, 2025, 8:58pm
2
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 .
khimru
February 13, 2025, 8:59pm
3
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
system
Closed
May 14, 2025, 8:59pm
4
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.