what is the easiest way to enforce that a field in a struct must not be an empty string ("")?
Example:
struct User{
name: String,
otherAttribute: Option<String>
}
user1 = User{"".toString(), "".toString()} //--> this should throw an error
I know I can implement the "new" trait for User and enforce special rules there but for large structs this is not a lot of fun.
Simple, use this:
// in its own module
struct User {
name: String,
otherAttribute: Option <String>
}
impl User {
pub fn new (name: &str, ...) -> Self {
if name == "" {
panic! (""); // or return None/Err
}
...
}
}
This will make User uncreatable from outside of the module it is located in, therefore the caller is forced to use User::new which validates the string. It will also make the calling shorter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With