我正在做一个数字猜谜游戏,猜出最接近的玩家获胜。
struct Player {
name: String,
balance: i32,
betamount: i32,
guess: i32
}
struct Game {
p1: Player,
p2: Player,
random_card: i32
}
impl Game {
pub fn start(&mut self) {
//start function
}
}
如何在start
函数中分配p1
和p2
的name
属性?允许这样做吗?
使用内部可变性模式
use std::cell::RefCell;
struct Player {
name: RefCell<String>,
balance: i32,
betamount: i32,
guess: i32
}
struct Game {
p1: Player,
p2: Player,
random_card: i32
}
impl Game {
pub fn start(&mut self) {
//start function
self.p1.name.replace_with(|_|"c".to_string());
self.p2.name.replace_with(|_|"c".to_string());
println!("{}",self.p1.name.borrow_mut())
}
}
fn main() {
let mut game = Game{
p1: Player {
name: RefCell::new("a".to_string()),
balance: 0,
betamount: 0,
guess: 0
},
p2: Player {
name: RefCell::new("b".to_string()),
balance: 0,
betamount: 0,
guess: 0
},
random_card: 0
};
game.start();
}
播放器对象是不可变的,但是如果我们想要改变它们的字段,我们可以将它们(字段)包装在RefCell或Cell中。