为什么在参数类型中使用"Self"会引发生命周期错误?

8

我目前在跟随https://raytracing.github.io/books/RayTracingInOneWeekend.html,但我正在使用Rust实现所有内容。以下是我的向量实现的一部分:

type Scalar = f64;

#[derive(Debug, Default, Clone)]
pub struct Vector {
    x: Scalar,
    y: Scalar,
    z: Scalar,
}

impl Vector {
    fn new(x: Scalar, y: Scalar, z: Scalar) -> Self {
        Self { x, y, z }
    }

    fn x(&self) -> Scalar {
        self.x
    }

    fn y(&self) -> Scalar {
        self.y
    }

    fn z(&self) -> Scalar {
        self.z
    }
}

impl std::ops::Mul<&Vector> for &Vector {
    type Output = Scalar;

    fn mul(self, rhs: Self) -> Self::Output {
        self.x() * rhs.x() + self.y() * rhs.y() + self.z() * rhs.z()
    }
}

当我尝试编译它时,我收到以下信息:

error[E0308]: method not compatible with trait
  --> src/point.rs:33:5
   |
33 |     fn mul(self, rhs: Self) -> Self::Output {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime mismatch
   |
   = note: expected fn pointer `fn(&point::Vector, &point::Vector) -> _`
              found fn pointer `fn(&point::Vector, &point::Vector) -> _`
note: the lifetime `'_` as defined on the impl at 30:20...
  --> src/point.rs:30:20
   |
30 | impl std::ops::Mul<&Vector> for &Vector {
   |                    ^
note: ...does not necessarily outlive the lifetime `'_` as defined on the impl at 30:20
  --> src/point.rs:30:20
   |
30 | impl std::ops::Mul<&Vector> for &Vector {
   |                    ^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
error: could not compile `raytracing`.

不过,如果我将 mul 函数的 Self 参数改为 &Vector,它就可以顺利编译了:

[...]
fn mul(self, rhs: &Vector) -> Self::Output {
[...]

这只是生命周期推断失败的情况吗?如果是这样,为什么会失败,因为编译器似乎已经正确推断了一切?

1个回答

5
这是因为生命周期省略规则,错误信息表明如下:

注意:在第30行20列实现中定义的生命周期'_...

该行代码:
impl std::ops::Mul<&Vector> for &Vector {

被解释为:

impl<'a, 'b> std::ops::Mul<&'a Vector> for &'b Vector // Self is &'b Vector

因此寿命不匹配,原因是:

fn mul(self, rhs: Self) -> Self::Output {

fn mul(self, rhs: &'b Vector) -> Self::Output {

&'a Vector != &'b Vector,所以它不能编译。因为rhs应该是&'a Vector

当您使用Self

impl std::ops::Mul<Self> for &Vector {

变成:

impl<'a> std::ops::Mul<&'a Vector> for &'a Vector {

fn mul(self, rhs: Self) -> Self::Output { 中,rhs 将具有正确的生命周期 <'a>
如果出现生命周期问题,请尝试明确指定以检查编译器是否出错。
最终代码不应包含任何 Self 关键字,以允许不同的生命周期。
impl std::ops::Mul<&Vector> for &Vector {
    type Output = Scalar;

    fn mul(self, rhs: &Vector) -> Self::Output {
        self.x() * rhs.x() + self.y() * rhs.y() + self.z() * rhs.z()
    }
}

明确的:

impl<'a, 'b> std::ops::Mul<&'a Vector> for &'b Vector {
    type Output = Scalar;

    fn mul(self, rhs: &'a Vector) -> Self::Output {
        self.x() * rhs.x() + self.y() * rhs.y() + self.z() * rhs.z()
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接