methods - 如何在方法中将结构的数据分配给 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 = &a
,self = &mut a
它没有工作。我应该如何将数据复制到self
这一a
行中?
我知道我的例子不是最优的,因为我可以只写self.x += 1
. 在我的完整项目中,我对其自身进行了艰苦的计算,a
因此self
我需要严格复制最后一行。
解决方案
推荐阅读
- java - 复制在 Go 中创建的 CRL
- import - 导入 Fortran 无格式二进制文件
- apache-kafka - Kafka 在哪里存储默认的 Broker 级别配置?
- laravel-5 - 无法禁用persistent_menu
- azure - Azure Active Directory - 在 java 中设置令牌到期
- php - POST /wp-admin/admin-ajax.php 400(错误请求)
- typescript - Typescript 泛型类型推断是更改对象形状后函数的“任意”
- python-3.x - 如何使用 Python Selenium 登录 gmail
- sql-server - 如何在 SQL Server 2012 中对月份列中的 varchar 周进行排序?
- javascript - 使用 css 动画时,是否有任何方法可以使连续动画按给定顺序无限重复