Rust Programming: Field Init Shorthand

0

Field init shorthand is a Rust syntax that allows you to omit the `:` when initializing a struct field with the same name as a variable.

fn build_user(email: String, username: String) -> User {

    User {

        active: true,

        username,

        email,

        sign_in_count: 1,

    }

}

As you can see, the `email` field is now initialized with the `email` parameter without the need for the `:`. This makes the code more concise and easier to read.

Note

  • It can only be used when the struct field name and the variable name are exactly the same.
  • It cannot be used when the struct field name and the variable name are only similar. For example, you cannot use field init shorthand to initialize a `username` field with a `user_name` variable.
  • It cannot be used when the struct field name and the variable name are different but have the same meaning. For example, you cannot use field init shorthand to initialize a `date_of_birth` field with a `birthdate` variable.

Post a Comment

0Comments
Post a Comment (0)