我目前一直关注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 {
[...]
这是否只是生存期推断失败的情况?如果是这样,为什么会失败,因为编译器似乎已经正确推断了所有内容?
由于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 for &Vector {
type Output = Scalar;
fn mul(self, rhs: Self) -> 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: &'b Vector) -> Self::Output {
self.x() * rhs.x() + self.y() * rhs.y() + self.z() * rhs.z()
}
}