我刚开始使用Rust,所以我的一些概念可能是错误的 . 如果是这样的话,我真的很感激修正 .
我正在关注lifetimes guide并尝试了一些例子 . 我稍微修改了矩形示例 .
我在第一个参数中更改了 compute_distance 函数以接受 Point . 然后我在调用 compute_distance 之前删除了 & 之前的 & .
这给了我以下错误:
不能脱离&-pointer的解除引用
如果我在 on_the_stack.origin 调用之前添加 & 以及在 compute_distance 函数中通过引用接受 Point ,它可以毫无障碍地工作 .
第二种方法对我有意义,但为什么我的原始方法会抛出错误?
use std::num::Float;
struct Point {
x : f64,
y : f64
}
struct Size {w: f64, h: f64}
struct Rectangle {origin: Point, size: Size}
#[cfg(not(test))]
fn main() {
let on_the_stack = &Rectangle{origin: Point {x: 1.0, y: 2.0},
size: Size {w: 3.0, h: 4.0}};
let on_the_heap = box Rectangle {origin: Point {x: 5.0, y: 6.0},
size: Size {w: 3.0, h: 4.0}};
println!("Distance: {}", compute_distance(on_the_stack.origin,&on_the_heap.origin));
}
fn compute_distance ( p1:Point,p2:&Point) -> f64 {
let x_d = p1.x - p2.x;
let y_d = p1.y - p2.y;
Float::sqrt(x_d * x_d + y_d * y_d)
}