我有一个带有Option<Vec<...>>的结构,在某个时候需要生成包含在其中的数据,或者在None的情况下生成一个零数组。我尝试过多种方法,但我总是遇到编译错误。我应该如何编码bar函数?
pub struct Foo {
pub data: Option<Vec<u32>>
}
impl Foo {
fn bar(&self) -> &Vec<u32> {
self.data.as_ref().unwrap_or_else(|| &vec![0, 10])
}
}
fn main() {
let foo = Foo { data: None };
println!("{:?}", foo.bar());
}> rustc main.rs
error[E0515]: cannot return reference to temporary value
--> main.rs:7:42
|
7 | self.data.as_ref().unwrap_or_else(|| &vec![0, 10])
| ^-----------
| ||
| |temporary value created here
| returns a reference to data owned by the current function
error: aborting due to previous error
For more information about this error, try `rustc --explain E0515`.发布于 2022-08-31 22:34:46
正如其他人所指出的,由于其他原因,返回一个片比较好,但它也使这个方法的实现更容易--您可以只获取一个静态数组的一个片段:
pub struct Foo {
pub data: Option<Vec<u32>>
}
impl Foo {
fn bar(&self) -> &[u32] {
self.data.as_deref().unwrap_or(&[0; 10])
}
}
fn main() {
let foo = Foo { data: None };
println!("{:?}", foo.bar());
}(游乐场)
https://stackoverflow.com/questions/73562275
复制相似问题