I have created a small program where I add users to a register. When I take an object oriented approach in Java, it is quite common to decompose functionality into smaller methods, so I have created addUser
and findUser
methods for Register
. When I compile this program I get the following compilation errors. I have read about borrowing, but could not find a way to fix this.
struct User {
userId: u8,
age: u8,
}
struct Register {
users: Vec<User>,
}
impl Register {
// Initialize
fn init() -> Register {
Register {
users: Vec::new()
}
}
// Add user to register, if user does not exist in register
fn addUser(&mut self, user: User) {
match self.findUser(user.userId) {
Some(u) => println!("User exists!"),
None => self.users.push(user),
};
}
// If user exists, return user, else return None
fn findUser(&self, userId: u8) -> Option<&User> {
for user in &self.users {
if user.userId == userId {
return Some(&user);
}
}
None
}
}
Compilation error message:
error[E0502]: cannot borrow `self.users` as mutable because `*self` is also borrowed as immutable
--> src/main.rs:18:21
|
16 | match self.findUser(user.userId) {
| ---- immutable borrow occurs here
17 | Some(u) => println!("User exists!"),
18 | None => self.users.push(user),
| ^^^^^^^^^^ mutable borrow occurs here
19 | };
| - immutable borrow ends here