gpt4 book ai didi

rust - 如何借用对Option 内部内容的引用?

转载 作者:行者123 更新时间:2023-12-03 11:27:10 33 4
gpt4 key购买 nike

如何从Option中提取引用,并将其与调用者的特定使用期限一起传递回去?

具体来说,我想从其中包含Box<Foo>Bar借用对Option<Box<Foo>>的引用。我以为我可以做到:

impl Bar {
fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
match self.data {
Some(e) => Ok(&e),
None => Err(BarErr::Nope),
}
}
}

...但是导致:

error: `e` does not live long enough
--> src/main.rs:17:28
|
17 | Some(e) => Ok(&e),
| ^ does not live long enough
18 | None => Err(BarErr::Nope),
19 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the body at 15:54...
--> src/main.rs:15:55
|
15 | fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
| _______________________________________________________^ starting here...
16 | | match self.data {
17 | | Some(e) => Ok(&e),
18 | | None => Err(BarErr::Nope),
19 | | }
20 | | }
| |_____^ ...ending here

error[E0507]: cannot move out of borrowed content
--> src/main.rs:16:15
|
16 | match self.data {
| ^^^^ cannot move out of borrowed content
17 | Some(e) => Ok(&e),
| - hint: to prevent move, use `ref e` or `ref mut e`

嗯好也许不吧。看起来像我想做的事与 Option::as_ref 有关,好像我可以做的那样:
impl Bar {
fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
match self.data {
Some(e) => Ok(self.data.as_ref()),
None => Err(BarErr::Nope),
}
}
}

...但是,这也不起作用。

完整代码我遇到了麻烦:
#[derive(Debug)]
struct Foo;

#[derive(Debug)]
struct Bar {
data: Option<Box<Foo>>,
}

#[derive(Debug)]
enum BarErr {
Nope,
}

impl Bar {
fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
match self.data {
Some(e) => Ok(&e),
None => Err(BarErr::Nope),
}
}
}

#[test]
fn test_create_indirect() {
let mut x = Bar { data: Some(Box::new(Foo)) };
let mut x2 = Bar { data: None };
{
let y = x.borrow();
println!("{:?}", y);
}
{
let z = x2.borrow();
println!("{:?}", z);
}
}

我有合理的把握要尝试做的事在这里有效。

最佳答案

首先,您不需要&mut self

匹配时,应匹配e作为引用。您正在尝试返回e的引用,但是其生存期仅适用于该match语句。

enum BarErr {
Nope
}

struct Foo;

struct Bar {
data: Option<Box<Foo>>
}

impl Bar {
fn borrow(&self) -> Result<&Foo, BarErr> {
match self.data {
Some(ref x) => Ok(x),
None => Err(BarErr::Nope)
}
}
}

关于rust - 如何借用对Option <T>内部内容的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63560794/

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