首页 > 解决方案 > 如何从函数更改实例?

问题描述

这是我的代码

struct AA{
    size:i8
}
impl AA{
    pub fn create()->Self{
        Self { size: 10 }
    }
    pub fn world(mut self)->Self{
        self.size+=2;
        self
    }
    pub fn say(self){
        println!("{}",self.size);
    }
}

//cannot move out of `*aa` which is behind a mutable reference
fn hello(aa: &mut AA){//this function will make a change
    aa.world();//                  <-- need to call world() from here
}

fn main() {
    let mut a=AA::create();
    hello(&mut a);
    a.say();//                     <-- need to call say() from here after hello() does the change
    //AA::create().world().say();  <-- this works
}

如何在 rust 中实现以下目标?

从主(),

  1. 创建实例
  2. 将实例传递给 world() 以便它可以更改实例
  3. 更改发生后,从 main 调用实例的 say()

标签: rust

解决方案


这种替代方案对您有用吗?

struct AA {
    size: i8,
}

impl AA {
    pub fn create() -> Self {
        Self { size: 10 }
    }
    pub fn world(mut self) -> Self {
        self.size += 2;
        self
    }
    pub fn say(self) {
        println!("{}", self.size);
    }
}

fn hello(aa: AA) -> AA {
    aa.world()
}

fn main() {
    let mut a = AA::create();
    a = hello(a);
    a.say();
}

注意 world 返回一个 Self 类型, hello 也返回AA。通过这种方式ahello()我们使用它并返回它的新版本,而不是传递一个可变引用。

另一种选择是两者都world接受say引用self而不是使用它们,在这种情况下,代码段将是:

    pub fn world(&self) -> Self {
        AA {
            size: self.size + 2,
        }
    }
    pub fn say(&self) {
        println!("{}", self.size);
    }

推荐阅读