I'm working through Rust by Example. I'm currently at TryFrom and TryInto. This is their code:
struct EvenNumber(i32);
impl TryFrom<i32> for EvenNumber {
type Error = ();
fn try_from(value: i32) -> Result<Self, Self::Error> {
if value % 2 == 0 {
Ok(EvenNumber(value))
} else {
Err(())
}
}
}
The implementation prevents the creation of an instance of EvenNumber with an odd number, but only if I call try_from (or try_into). I can still create an EvenNumber(1337) directly.
In Java (and related languages), one would validate instance creation inside a constructor, e.g.:
class EvenNumber {
public final int value;
public EvenNumber(int value) {
if (value % 2 != 0) {
throw new IllegalArgumentException("value is odd");
}
this.value = value;
}
}
How to do this in Rust?