rust - 错误[E0308]:类型不匹配 - 预期结构 `Test`,发现 `&Test`
问题描述
我正在尝试为 Test 结构创建函数实现 add_test,但出现以下错误。
#[derive(Debug)]
pub struct Test {
a: i32,
b: i32,
}
impl Test {
pub fn new(x: i32, y: i32) -> Self {
Test {
a: x,
b: y,
}
}
pub fn add_test(&self, z: i32) -> Self {
self.a += z;
self.b += z;
self
}
}
fn main() {
println!("{:?}", Test::new(3, 2));
}
错误:
error[E0308]: mismatched types
--> src/main.rs:20:9
|
16 | pub fn add_test(&self, z: i32) -> Self {
| ---- expected `Test` because of return type
...
20 | self
| ^^^^ expected struct `Test`, found `&Test`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground`
To learn more, run the command again with --verbose.
我应该怎么做才能修复它?我尝试取消引用,但编译器询问了结构的“复制”impl ...
解决方案
根据您的其他要求,您可以通过三种方式解决此问题:
进入self
并add_test
返回修改后的self
:
pub fn add_test(self, z: i32) -> Self {
self.a += z;
self.b += z;
self
}
通过可变引用获取self
并且不返回任何内容:
pub fn add_test(&mut self, z: i32) {
self.a += z;
self.b += z;
}
Self
返回具有修改值的新类型实例:
pub fn add_test(&self, z: i32) -> Self {
Test {
a: self.a + z,
b: self.b + z,
}
}
推荐阅读
- python - 对象在 for ... 语句中使用或运算符读取为列表,但使用和运算符读取为布尔值
- java - Java 独立应用程序 - 如何读取 (http) cookie
- php - Laravel Config::set() 似乎不适用于排队作业
- rstudio - 如何检查在 R Studio 中运行的脚本的进度?
- mysql - MySQL MIN 查询不适用于计算的距离
- python - Keras 中预训练的 ResNet101 在哪里以及如何获得原始特征?
- java - 从 api 调用接收 null
- c - 为什么这个函数不纯?
- swift - switch 声明的预期声明
- c++ - C++ - 将 void 函数值写入文件