How to use struct update syntax with immutable borrow?

Viewed 33

I am getting an error while creating an instance of struct using struct update syntax:

struct User {
    username: String,
    email: String,
    active: bool,
    sign_in_count: u64,
}

fn create_user(username: &str, email: &str) -> User {
    User {
        username: username.to_string(),
        email: email.to_string(),
        active: true,
        sign_in_count: 1,
    }
}

fn create_user_from_template(username: &str, email: &str, user: &User) -> User {
    User {
        username: username.to_string(),
        email: email.to_string(),
        ..user
    }
}

fn print_user(user: &User) {
    println!("username: {}, email: {}", user.username, user.email);
}

fn main() {
    let user1 = create_user("abcd", "abcd@gmail.com");
    print_user(&user1);
    let user2 = create_user_from_template("xyz", "xyz@gmail.com", &user1);
    print_user(&user2);
}
error[E0308]: mismatched types
  --> src/main.rs:21:11
   |
21 |         ..user
   |           ^^^^ expected struct `User`, found `&User`

For more information about this error, try `rustc --explain E0308`.

Is this possible? What do I need to do?

1 Answers

user is a passed in as a reference to your create_user_from_template function, (as the &User type) so all you need to do it dereference it: ..*user.

Related