一个游戏的最小例子,玩家拥有一个位置,并随着时间的推移而行走.以下内容进行了编译:
use std::thread::sleep;
use std::time::Duration;
struct Player {
position: usize,
}
impl Player {
fn new() -> Self {
Self { position: 0 }
}
}
impl Player {
fn get_position(&self) -> usize {
self.position
}
}
impl Player {
fn walk(&mut self) {
self.position += 1;
}
}
fn main() {
let mut player = Player::new();
loop {
player.walk();
sleep(Duration::from_secs(1));
}
}
如果球员borrow 而不是拥有这个位置,它不会编译:
use std::thread::sleep;
use std::time::Duration;
struct Player<'a> {
position: &'a mut usize,
}
impl<'a> Player<'a> {
fn new(position: &'a mut usize) -> Self {
Self { position }
}
}
impl<'a> Player<'a> {
fn get_position(&'a self) -> usize {
*self.position
}
}
impl<'a> Player<'a> {
fn walk(&'a mut self) {
*self.position += 1;
}
}
fn main() {
let mut position = 0;
let mut player = Player::new(&mut position);
loop {
player.walk();
sleep(Duration::from_secs(1));
}
}
错误为:
error[E0499]: cannot borrow `player` as mutable more than once at a time
--> src/main.rs:30:9
|
30 | player.walk();
| ^^^^^^
| |
| `player` was mutably borrowed here in the previous iteration of the loop
| first borrow used here, in later iteration of loop
我不明白为什么第二个程序不能编译,而第一个程序可以.我知道编译器不接受多个可变borrow ,但第一个不也是这样吗?该程序运行walk函数,该函数要求对self的可变引用,与第二个程序的方式相同.
在这样的情况下,程序需要borrow struct 中的数据,然后修改它,什么是好的解决方案?