Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 241
Jimmy Foobar Avatar asked Oct 25 '25 05:10

Jimmy Foobar


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.

like image 162
Rafaelplayerxd YT Avatar answered Oct 26 '25 18:10

Rafaelplayerxd YT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!