作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
下面的代码给出了错误“无法移出借用的内容”。我知道这里已经有很多关于此的问题。我认为每个使用 Rust 的人都曾一度发现自己在这里,试图弄清楚所有权究竟是怎么回事。我想我知道这里发生了什么以及如何解决它,我只是不知道如何在这种特殊情况下使用引用。如果有更惯用的方法来完成我正在尝试的事情,请在评论中告诉我。
我可以看到我试图取得所有权的地方,但我不确定如何使用引用。
让我们看一个最小的例子:
/* I define two shape structs. The main point here is that they
are not default copyable, unlike most primitive types */
struct Circle {
center_x: f64,
center_y: f64,
r: f64,
}
struct Square {
center_x: f64,
center_y: f64,
length: f64,
}
/* this enum will be a container for shapes because we don't know
which shape we might need. */
enum Shape {
// these are scoped differently, so it's okay.
Circle(Circle),
Square(Square),
}
/* I'm making cookies, each cookie has a shape */
struct Cookie {
shape: Shape,
}
/* All of the above was setup, here is where we find errors */
impl Cookie {
/* checks if two cookies have the same radius. squares -> false */
fn has_same_radius(&self, other_cookie: &Cookie) -> bool {
// fn has_same_radius(self, other_cookie: Cookie) -> bool {
/* swapping the above two lines will remedy the error,
but I don't want this function to take ownership of either */
match self.shape {
/* As soon as I declare c1, I'm taking ownership of self.shape
and therefore self as well. This is in spite of the fact
that I never plan to alter anything.
How can I simply use a reference to c1> */
Shape::Circle(c1) => match other_cookie.shape {
/* same thing here with c2 */
Shape::Circle(c2) => {
if c2.r == c1.r {
return true;
}
}
Shape::Square(_) => return false,
},
Shape::Square(_) => return false,
}
return false;
}
}
当我在 Shape
枚举上进行匹配时,我只想引用封装在 Shape
中的参数,但由于我没有使用引用,所以我试图采用整个 Cookie 结构的所有权。
最佳答案
改变
....
Shape::Circle(c1) => ...
....
Shape::Circle(c2) => ...
....
到
....
Shape::Circle(ref c1) => ...
....
Shape::Circle(ref c2) => ...
....
let ref x = y;
基本上是 let x = &y;
的模式匹配版本。
关于rust - 引用枚举中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37267060/
我是一名优秀的程序员,十分优秀!