billy voiderer
billy voiderer

Reputation: 101

Option map() returns a reference to data owned by the current function

I want to do something like this:

struct Foo {
    pub name: String,
}

fn is_empty(s: &str) -> bool {
    s.len() == 0
}

fn main() {
    let entity = Some(Foo { name: "some-name".to_string() });
    
    let name: &str = entity
        .map(|it| it.name.as_ref())
        .unwrap_or( "onother-name");

    println!("is it empty: {}", is_empty(name));
}

but it compiles with error: "returns a reference to data owned by the current function". How can I fix it elegantly? Make a copy of string and use String instead &str seems to me non optimal. Thanks

Upvotes: 1

Views: 1013

Answers (1)

Dogbert
Dogbert

Reputation: 222158

Option::map consumes the Option. You should call .as_ref() on the Option first to get Option<&T> and then call .map on it:

struct Foo {
    name: String,
}

fn is_empty(s: &str) -> bool {
    s.len() == 0
}

fn main() {
    let entity = Some(Foo {
        name: "some-name".to_string(),
    });

    let name: &str = entity
        .as_ref()
        .map(|it| it.name.as_ref())
        .unwrap_or("onother-name");

    println!("is it empty: {}", is_empty(name));
}

Playground

Upvotes: 4

Related Questions