Error "cannot move out of borrowed content" in Rust: how to fix?
Hi everyone! I started learning Rust and encountered an error I can't understand. I have a `User` struct and a function that should modify its `name` field. Here's the code:
```rust
struct User {
name: String,
age: u32,
}
fn update_name(user: &User, new_name: String) {
user.name = new_name; // Error here
}
fn main() {
let user = User {
name: String::from("Alice"),
age: 30,
};
update_name(&user, String::from("Bob"));
println!("{}", user.name);
}
```
The compiler outputs: `cannot move out of borrowed content` and `cannot move out of behind a shared reference`. I understand that I'm passing `&User` — this is an immutable reference, but I want to change the `name` field. If I change the signature to `&mut User`, the error changes to `cannot borrow immu
No answers yet.
Log in to leave an answer