如何将结构的数据分配到的方法自我?

问题描述 投票:0回答:1

我想修改临时存储到另一个变量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本身,所以我需要在最后一行复制严格。

methods reference rust
1个回答
4
投票

您需要取消引用self

*self = a;

没有什么关于self或事实,这是一个独特的方法。同样的事情是因为你所替换值的任何可变引用真实的。

也可以看看:

© www.soinside.com 2019 - 2024. All rights reserved.