【发布时间】:2015-01-04 18:37:38
【问题描述】:
我刚开始使用 Rust,所以我的一些概念可能是错误的。如果是这种情况,我真的很感激更正。
我正在关注lifetimes guide 并尝试了一些示例。我稍微修改了矩形示例。
我将compute_distance 函数更改为在第一个参数中按值接受Point。
然后我在对compute_distance 的调用中删除了on_the_stack.origin 之前的&。
这给了我以下错误:
无法脱离
&-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)
}
【问题讨论】:
-
我看到你链接到 0.12 文档。请注意,为了准备 1.0 alpha/beta/release,Rust 正在迅速变化。建议跟踪每晚构建(和文档)。
-
哇哦,你是对的。 nightly docs 上的链接似乎完全不同。感谢您的提示!
标签: rust