首页 > 解决方案 > 错误[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 ...

标签: rust

解决方案


根据您的其他要求,您可以通过三种方式解决此问题:

进入selfadd_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,
    }
}

推荐阅读