我有一个带有Option<String>
字段的结构类型。在我的可选类型的方法中,我想匹配该字段并将值提取到本地范围中。我知道我需要说服借用检查器不要丢弃我的结构类型中指向的内存;我不知道该怎么做。
对于上下文,这是一个明显错误的示例。
struct Cell {
data: Option<String>,
}
impl Cell {
fn match_me(&self) -> String {
match self.data {
Some(x) => x,
None => "match failed".to_owned(),
}
}
}
fn main() {
let data = Some("hello".to_owned());
let my_cell = Cell { data };
let result = my_cell.match_me();
print!("{}", result);
}
这个程序显然是错误的,因为我将内部的值移动x
到本地范围内,这意味着当方法返回时它将被删除;但是,由于该结构比方法调用的寿命更长,因此该值仍然可以在其他地方访问,这将在出现错误后产生使用。
由于我想使用该Some()
值而不丢弃它,我想我应该引用计数它。尝试二:
use std::rc::Rc;
struct Cell {
data: Rc<Option<Rc<String>>>,
}
impl Cell {
fn match_me(&self) -> String {
let local = self.data.clone();
match *local {
Some(x) => *Rc::clone(&x),
None => "match failed".to_owned(),
}
}
}
fn main() {
let data = Rc::new(Some(Rc::new("hello".to_owned())));
let my_cell = Cell { data };
let result = my_cell.match_me();
print!("{}", result);
}
但是,尽管克隆了这些引用,但我仍然遇到借用错误。
Compiling playground v0.0.1 (file:///playground)
error[E0507]: cannot move out of borrowed content
--> src/main.rs:10:15
|
10 | match *local {
| ^^^^^^ cannot move out of borrowed content
11 | Some(x) => *Rc::clone(&x),
| - hint: to prevent move, use `ref x` or `ref mut x`
error[E0507]: cannot move out of borrowed content
--> src/main.rs:11:24
|
11 | Some(x) => *Rc::clone(&x),
| ^^^^^^^^^^^^^^ cannot move out of borrowed
content
除了clone
物品本身,我真的没有任何追索权吗?