gpt4 book ai didi

rust - 如何获得期权的值(value)或设置它为空?

转载 作者:行者123 更新时间:2023-12-03 11:39:57 26 4
gpt4 key购买 nike

我想获取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

最佳答案

在我看来,就像您想要 get_or_insert_with() method一样。当OptionNone时,这将执行闭包并将结果用作新值:

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())
}

关于rust - 如何获得期权的值(value)或设置它为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60008354/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com