下面的代码给出了错误“无法移出借来的内容”。我知道这里已经有很多问题了。我认为每个使用Rust的人都会在某个方面发现自己,试图找出所有权的具体内容。我想我知道这里发生了什么以及如何解决它,我只是不知道在这种特殊情况下如何使用引用。如果有一种更惯用的方式来完成我正在尝试的内容,请在评论中告诉我。
我可以看到我正在尝试取得所有权,但我不确定如何使用参考。
让我们看一个极小的例子:
import requests
response = requests.get(
url='https://api.instagram.com/v1/tags/{tagname}/media/recent'.format(tagname='testing'),
params={
'access_token': YOUR_TOKEN,
'count': 33,
}
).json()
当我在/* 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
中封装的参数,但由于我没有使用引用,我试图取得整个Cookie结构的所有权。
答案 0 :(得分:3)
更改
....
Shape::Circle(c1) => ...
....
Shape::Circle(c2) => ...
....
到
....
Shape::Circle(ref c1) => ...
....
Shape::Circle(ref c2) => ...
....
let ref x = y;
基本上是let x = &y;
的模式匹配版本。
答案 1 :(得分:2)
正如WiSaGan所指出的,您必须使用ref
模式来创建对包含值的引用。您还可以同时简化与两个形状匹配的代码:
impl Cookie {
fn has_same_radius(&self, other: &Cookie) -> bool {
match (&self.shape, &other.shape) {
(&Shape::Circle(ref c1), &Shape::Circle(ref c2)) => c1.r == c2.r,
_ => false,
}
}
}