我想获取name
如果它不为空或设置新值。我怎么能这样做?
#[derive(Debug)]
struct App {
name: Option<String>,
age: i32,
}
impl App {
fn get_name<'a>(&'a mut self) -> &'a Option<String> {
match self.name {
Some(_) => &self.name,
None => {
self.name = Some(String::from("234"));
&self.name
}
}
}
}
fn main() {
let mut app = App {
name: None,
age: 10,
};
println!("{:?} and name is {}", &app, &app.get_name().unwrap())
}
我得到的错误是:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:25:44
|
25 | println!("{:?} and name is {}", &app, &app.get_name().unwrap())
| ^^^^^^^^^^^^^^ cannot move out of borrowed content
error[E0502]: cannot borrow `app` as mutable because it is also borrowed as immutable
--> src/main.rs:25:44
|
25 | println!("{:?} and name is {}", &app, &app.get_name().unwrap())
| ---------------------------------------^^^---------------------
| | | |
| | | mutable borrow occurs here
| | immutable borrow occurs here
| immutable borrow ends here
|
= note: this error originates in a macro outside of the current crate
答案 0 :(得分:4)
在我看来,你想要get_or_insert_with()
method。这会在Option
为None
时执行关闭,并将结果用作新值:
fn get_name(&mut self) -> String {
self.name.get_or_insert_with(|| String::from("234"))
}
如果您已经有值要插入,或者创建的价值不贵,您还可以使用get_or_insert()
method:
fn get_name(&mut self) -> &String {
self.name.get_or_insert(String::from("234"))
}
您还需要更改main()
功能以避免借用问题。一个简单的解决方案是在您的结构上导出Clone
,然后在.clone()
的调用中println!()
导出:
fn main() {
let mut app = App {
name: None,
age: 10,
};
println!("{:?} and name is {}", app.clone(), app.get_name())
}