首页 > 解决方案 > 如何在方法中将结构的数据分配给 self?

问题描述

我正在尝试将其修改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它没有工作。我应该如何将数据复制到self这一a行中?

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

标签: methodsreferencerust

解决方案


您需要取消引用self

*self = a;

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

也可以看看:


推荐阅读