gpt4 book ai didi

operator-overloading - 为引用定义运算符时,借用的值不会持续足够长的时间

转载 作者:行者123 更新时间:2023-11-29 08:05:25 25 4
gpt4 key购买 nike

为什么借用检查器不喜欢此代码中的最后一个添加操作:

use std::ops::Add;

#[derive(Debug)]
pub struct Vector(f64, f64, f64);

impl<'r> Add for &'r Vector {
type Output = Vector;

fn add(self, _rhs: &'r Vector) -> Vector {
Vector(self.0 + _rhs.0, self.1 + _rhs.1, self.2 + _rhs.2)
}
}

fn main() {
let v1 = &Vector(1.0, 2.0, 3.0);
let v2 = &Vector(13.0, 12.0, 11.0);

println!("{:?}", v2.add(v1)); // Ok
println!("{:?}", v1.add(v2)); // Ok

println!("{:?}", v2 + v1); // Ok
println!("{:?}", v1 + v2); // error: borrowed value does not live long enough
}

注释掉最后一个 println! 使这段代码有效,这看起来像是一个编译器错误。

最佳答案

你有这个代码:

impl<'r> Add for &'r Vector {
type Output = Vector;

fn add(self, _rhs: &'r Vector) -> Vector {
Vector(self.0 + _rhs.0, self.1 + _rhs.1, self.2 + _rhs.2)
}
}

展开后,看起来有点像这样:

impl<'r> Add<&'r Vector> for &'r Vector {
type Output = Vector;

fn add(self: &'r Vector, _rhs: &'r Vector) -> Vector {
Vector(self.0 + _rhs.0, self.1 + _rhs.1, self.2 + _rhs.2)
}
}

也就是说,您已经为两个可以被限制为具有重叠生命周期的引用实现了特征,并且 'r 的值将是这些生命周期的交集。如果您允许添加两个不同生命周期的引用,它会起作用:

impl<'r, 's> Add<&'s Vector> for &'r Vector {
type Output = Vector;

fn add(self, rhs: &'s Vector) -> Vector {
Vector(self.0 + rhs.0, self.1 + rhs.1, self.2 + rhs.2)
}
}

我承认我不完全理解为什么直接调用 add 会有所不同。据我所知,如果它能够为一个方向创建相交的生命周期,我希望它能够走向另一个方向。


此外,您应该在这里使用_rhs 作为变量名。前面的下划线表示“此变量未使用”,但您肯定会使用它。

关于operator-overloading - 为引用定义运算符时,借用的值不会持续足够长的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34520459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com