请帮助我理解,还有什么更好的方法来编写代码,这将使闭包变量发生变化并改变struct方法的行为
fn main() {
let me = Person {
name: String::from("Anton"),
age: 26,
};
let mut x = 0;
let mut counter = |x: &mut i32| *x += 1;
println!("x equals: {}", x);
me.print_info(&mut counter, &mut x).print_info(&mut counter, &mut x);
println!("x equals: {}", x);
}
struct Person {
name: String,
age: u32,
}
impl Person {
fn print_info(&self, counter: &mut FnMut(&mut i32), x: &mut i32) -> &Self {
if *x > 0 {
println!("I never repeat twice");
} else {
println!("My name is {} and I am {} years old", self.name, self.age);
}
counter(x);
self
}
}