HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustModerate

How do I borrow a reference to what is inside an Option<T>?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howinsideoptionborrowwhatreference

Problem

How do I pull a reference out of an Option and pass it back with the specific lifespan of the caller?

Specifically, I want to borrow a reference to a Box from a Bar that has an Option> in it. I thought I would be able to do:

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


...but that results in:

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, 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


Hm, ok. Maybe not. It looks vaguely like what I want to do is related to Option::as_ref, like maybe I could do:

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


...but, that doesn't work either.

Full code I'm having trouble with:

```
#[derive(Debug)]
struct Foo;

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

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

impl Bar {
fn borrow(&mut self) -> Result, Ba

Solution

First of all, you don't need &mut self.

When matching, you should match e as a reference. You are trying to return a reference of e, but the lifetime of it is only for that match statement.

enum BarErr {
    Nope
}

struct Foo;

struct Bar {
    data: Option>
}

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

Code Snippets

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

Context

Stack Overflow Q#22282117, score: 31

Revisions (0)

No revisions yet.