Rust 获取或创建不需要的字段选项<;T>;
有一种方法可以在db vocab中实现get或create like upsert,无需输入字段 在以下代码中,由于借用了self.option,因此失败Rust 获取或创建不需要的字段选项<;T>;,rust,Rust,有一种方法可以在db vocab中实现get或create like upsert,无需输入字段 在以下代码中,由于借用了self.option,因此失败 #[derive(Debug)] struct A { option: Option<i32>, } impl A { fn new() -> Self { Self { option: None } } fn option_or_new(&mut self) -&
#[derive(Debug)]
struct A {
option: Option<i32>,
}
impl A {
fn new() -> Self {
Self { option: None }
}
fn option_or_new(&mut self) -> &i32 {
if let Some(i) = &self.option { // `self.option` is borrowed here
&i
} else {
let i = 0;
self.option = Some(i); // cannot assign to `self.option` because it is borrowed
self.option.as_ref().unwrap()
}
}
}
fn main() {
let mut a = A::new();
let i = a.option_or_new();
println!("{}",i);
}
#[派生(调试)]
结构A{
选项:选项,
}
暗示{
fn new()->Self{
自我{选项:无}
}
fn选项\u或\u新建(&mut self)->&i32{
如果让一些(i)=&self.option{/`self.option`借用到这里
&我
}否则{
设i=0;
self.option=Some(i);//无法分配给'self.option',因为它是借用的
self.option.as_ref().unwrap()
}
}
}
fn main(){
让mut a=a::new();
设i=a.选项_或_new();
println!(“{}”,i);
}
我必须使用不安全的代码来解决此问题,或者它是否存在一种惯用的方式?您可以使用或:
impl A{
fn选项\u或\u新建(&mut self)->&i32{
self.option.get\u或\u insert(0)
}
}
您可以使用或:
impl A{
fn选项\u或\u新建(&mut self)->&i32{
self.option.get\u或\u insert(0)
}
}