如何在方法中将结构的数据分配给self?

Fom*_*aut 0 methods reference rust

我正在尝试修改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?
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到错误:

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?
    }
}
Run Code Online (Sandbox Code Playgroud)

我曾尝试self = &aself = &mut a,也没有工作。我应该如何将数据复制到selfa这一行?

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

She*_*ter 5

您需要取消引用self

*self = a;
Run Code Online (Sandbox Code Playgroud)

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

也可以看看: