【发布时间】:2020-09-27 19:46:47
【问题描述】:
我正在实现处理长度为k * n 的向量并创建
k 长度点 n 引用原始向量的切片:
struct Point<'a> {
values: &'a [f32],
}
impl<'a> Point<'a> {
pub fn new(values: &'a [f32]) -> Self {
Point { values }
}
pub fn dist_euclidian(&self, point: &Point) -> Result<f32, &str> {
unimplemented!()
}
}
当我尝试测试它时:
#[test]
fn test_euclidian_distance() {
let mut v1 = vec![7.0, 11.0];
let mut v2 = vec![40.0, -27.0];
let p1: Point = Point::new(&v1[..]);
let p2: Point = Point::new(&v2[..]);
assert!((p1.dist_euclidian(&p2).unwrap() - 50.32).abs() <= 0.01);
v1[0] = 0.0;
v1[1] = -4.0;
v2[0] = 8.0;
v2[1] = 100.0;
assert!((p1.dist_euclidian(&p2).unwrap() - 104.3072).abs() <= 0.01);
}
我收到以下错误:
error[E0502]: cannot borrow `v1` as mutable because it is also borrowed as immutable
--> src/k_means/point.rs:56:9
|
51 | let p1: Point = Point::new(&v1[..]);
| -- immutable borrow occurs here
...
56 | v1[0] = 0.0;
| ^^ mutable borrow occurs here
...
61 | assert!((p1.dist_euclidian(&p2).unwrap() - 104.3072).abs() <= 0.01);
| -- immutable borrow later used here
error[E0502]: cannot borrow `v1` as mutable because it is also borrowed as immutable
--> src/k_means/point.rs:57:9
|
51 | let p1: Point = Point::new(&v1[..]);
| -- immutable borrow occurs here
...
57 | v1[1] = -4.0;
| ^^ mutable borrow occurs here
...
61 | assert!((p1.dist_euclidian(&p2).unwrap() - 104.3072).abs() <= 0.01);
| -- immutable borrow later used here
error[E0502]: cannot borrow `v2` as mutable because it is also borrowed as immutable
--> src/k_means/point.rs:58:9
|
52 | let p2: Point = Point::new(&v2[..]);
| -- immutable borrow occurs here
...
58 | v2[0] = 8.0;
| ^^ mutable borrow occurs here
...
61 | assert!((p1.dist_euclidian(&p2).unwrap() - 104.3072).abs() <= 0.01);
| --- immutable borrow later used here
error[E0502]: cannot borrow `v2` as mutable because it is also borrowed as immutable
--> src/k_means/point.rs:59:9
|
52 | let p2: Point = Point::new(&v2[..]);
| -- immutable borrow occurs here
...
59 | v2[1] = 100.0;
| ^^ mutable borrow occurs here
60 |
61 | assert!((p1.dist_euclidian(&p2).unwrap() - 104.3072).abs() <= 0.01);
| --- immutable borrow later used here
有没有一种安全的方式来做我打算做的事情?
【问题讨论】:
标签: rust slice lifetime unsafe ownership