Any shortcut for conditions based on Option types?

I frequently am setting a &str field in a struct based on an Option type that only must be transformed if it is Some

Ob{
  id: if person.is_some() {
    Some(person.unwrap().id)
  } else {
    None
  }
}

In other languages I would (unknowingly) be (probably) cloning person.id to the heap (as a String) when using more concise syntax like:

Ob{
  id: person.map(|p| p.id) // p.id goes out of scope
}

In Rust, once leaving the scope of the map closure id is garbage, so I can't benefit from the conciseness of map with &str type and the alternative if statement is a lot of typing. Is there anyway to get the conciseness of map with the correct scoping of the above if statement while keeping the type of &str for efficiency?

The version with map looks identical to the other version to me, can you clarify what error you are getting about p.id going out of scope?

Option::as_ref is often useful in these situations.

For more specific advice, it would be useful to have a concrete example of a case where your if expression works but map does not. In general, these should be equivalent. For example, in this playground both of them work fine.

2 Likes

person.as_ref().map(|p| p.id)

You can also use:

if let Some(p) = &person {
    Some(p.id)
1 Like

Thanks for all the suggestions, I messed up in my posting, sorry! There is no difference, just my tired eye balls missing details!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.