How to enforce that a string must not be empty in Rust?

Viewed 323

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.

1 Answers

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.

Related