I have a simple struct with one string field:
pub struct Chunk {
signature: String
}
This string field cannot be just any string, there are bunch of constraints that it needs to satisfy (and if string passed to constructor does not satisfy these constraints, construction of struct should fail).
In object-oriented languages like C++, I would make the explicit constructor that does the needed checks, what is the correct way to do this in Rust?
I came up with this code:
impl Chunk {
pub fn new(s: String) -> Option<Chunk> {
if constraints_fail {
None
} else {
Some(Chunk{signature: s})
}
}
}
I'm not sure if this is a correct approach, since technically the struct can still be instantiated with invalid string parameter without ever calling this function.