As I understand it, that requires dependent types, which Rust does not have. This doesn't require dependent types (see comments) but Rust still doesn't have the support needed.
As a workaround, you could create a newtype that you verify yourself:
#[derive(Debug)]
struct Age(u16);
impl Age {
fn new(age: u16) -> Option<Age> {
if age <= 100 {
Some(Age(age))
} else {
None
}
}
}
fn main() {
let age1 = Age::new(30);
let age2 = Age::new(500);
println!("{:?}, {:?}", age1, age2);
assert_eq!(
std::mem::size_of::<Age>(),
std::mem::size_of::<u16>()
);
}
Of course, it doesn't behave exactly like a u16
, but you don't want it to, either! For example, a u16
can go beyond 100... You'd have to reason out if it makes sense to add/subtract/multiply/divide etc your new type as well.
For maximum safeguarding, you should move your type and any associated functions into a module. This leverages Rust's visibility rules to prevent people from accidentally accessing the value inside the newtype and invalidating the constraints.
You may also want to implement TryFrom
(from u16
to your type) or From
(from your type to u16
) to better integrate with generic code.
An important thing to note is that this newtype takes the same amount of space as a u16
- the wrapper type is effectively erased when the code is compiled. The type checker makes sure everything meshes before that point.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…