以适当的方式在struct方法中使用闭包

时间:2019-05-01 09:37:17

标签: rust

请帮助我理解,还有什么更好的方法来编写代码,这将使闭包变量发生变化并改变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
    }
}

0 个答案:

没有答案