我目前在跟随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 {
[...]
这只是生命周期推断失败的情况吗?如果是这样,为什么会失败,因为编译器似乎已经正确推断了一切?