【问题标题】:How to assign data of a struct into self in a method?如何在方法中将结构的数据分配给 self?
【发布时间】:2019-02-05 21:26:30
【问题描述】:

我正在尝试修改临时存储到另一个变量中的self。在最后一步,我想将变量中的所有数据复制到self

struct A {
    x: i32,
}

impl A {
    fn new() -> Self {
        Self { x: 0 }
    }

    fn change(&mut self) {
        let mut a = Self::new();
        a.x += 1;

        self = a; // How to copy data from a variable into self?
    }
}

我得到错误:

error[E0308]: mismatched types
  --> src/lib.rs:14:16
   |
14 |         self = a; // How to copy data from a variable into self?
   |                ^
   |                |
   |                expected &mut A, found struct `A`
   |                help: consider mutably borrowing here: `&mut a`
   |
   = note: expected type `&mut A`
              found type `A`

我尝试了self = &aself = &mut a,但没有成功。我应该如何将这一行中的a中的数据复制到self

我知道我的例子不是最优的,因为我可以写self.x += 1。在我的完整项目中,我对 a 进行了艰苦的计算,其中包括 self 本身,因此我需要严格复制到最后一行。

【问题讨论】:

    标签: methods reference rust


    【解决方案1】:

    你需要取消引用self

    *self = a;
    

    self 或这是一种方法这一事实并没有什么独特之处。对于替换值的 any 可变引用也是如此。

    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-02
      • 2020-04-02
      相关资源
      最近更新 更多