Rust 铁锈封闭剂的再利用
我正在尝试生成一个Rust 铁锈封闭剂的再利用,rust,closures,borrow-checker,borrowing,Rust,Closures,Borrow Checker,Borrowing,我正在尝试生成一个Vec: 我知道我不能在元组的两个元素中都使用点,但是当我尝试存储引用时,我得到了一个关于生存期的错误。我假定您的点结构如下所示: #[derive(Debug)] struct Point(f64, f64); impl Point { fn new(x: f64, y: f64) -> Self { Point(x, y) } fn origin() -> Self { Point(0.,0.) } fn distance_to(&am
Vec
:
我知道我不能在元组的两个元素中都使用
点
,但是当我尝试存储引用时,我得到了一个关于生存期的错误。我假定您的点
结构如下所示:
#[derive(Debug)]
struct Point(f64, f64);
impl Point {
fn new(x: f64, y: f64) -> Self { Point(x, y) }
fn origin() -> Self { Point(0.,0.) }
fn distance_to(&self, other: &Point) -> f64 {
((other.0 - self.0).powi(2) + (other.1 - self.1).powi(2)).sqrt()
}
}
现在让我们看一个更简单的示例,它不会编译:
let x = Point::new(2.5, 1.0);
let y = x;
let d = x.distance_to(&y);
这就产生了错误:
错误[E0382]:使用移动值:`x`
--> :15:13
|
14 |设y=x;
|-价值转移到这里
15 |设d=x.u到(&y)的距离;
|^移动后此处使用的值
|
=注意:发生移动是因为'x'具有'Point'类型,该类型不实现'Copy'特性
由于x
已被移动到y
,因此现在无法使用引用来调用distance\u to
函数
这里需要注意的重要一点是顺序很重要-如果我们交换行,我们可以通过借用x
调用distance\u to
,借用将结束,然后x
可以移动到y
let x = Point(0., 0.);
let d = x.distance_to(&y);
let y = x; // compiles
在您的例子中,构造元组时也会发生类似的事情point
被移动到元组中,然后尝试借用它来形成第二个元素。最简单的解决方案是执行与此处相同的操作:交换元组元素的顺序
let points_and_distances = points_in_grid
.map(|point| (point.distance_to(&origin), point))
.collect::<Vec<(f64, Point)>>(); // compiles
请您提供一个完整的可编译(即使有错误)示例,最好是在play.rust-lang.org上运行的?更容易确定您遇到的错误和位置,并提出修复建议。换句话说,
Point
无法实现。您还可以使用一个临时变量-.map(| point |{let d=point.distance_to(&origin);(point,d)})
。
let points_and_distances = points_in_grid
.map(|point| (point.distance_to(&origin), point))
.collect::<Vec<(f64, Point)>>(); // compiles
.map(|(a, b)| (b, a))