为什么使用“ Self”作为参数类型会引起生命周期错误?

问题描述 投票:7回答:1

我目前与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`.

但是,如果我将Self函数上的mul参数更改为&Vector,则可以正常编译:

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

这是否只是生存期推断失败的情况?如果是这样,为什么会失败,因为编译器似乎已经正确推断了所有内容?

rust type-inference lifetime
1个回答
5
投票

由于lifetime elision的规则,错误消息告诉它:

注意:生命周期'_,如在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()
    }
}
    
© www.soinside.com 2019 - 2024. All rights reserved.