Is there a way to map option using ref without consuming it?

When I map on option the operation consumes the self which means i cannot use the original option anymore.

So what want to do is to be able to map on an option multiple times without consuming it and just to return a new option with a value.

What I am trying to do is the same thing as from elm language.

let user = User{

let maybeName =|v|
let maybeAnother =|v|v.another.clone()) 
// this is not possible right now because the user is consumed earlier while getting the name

If Creds is Clone, you could clone the Option and map on this clone.

Do you mean something like user.credentials.as_ref().map(|&v|

1 Like

then i would have to clone the entire struct every time

I guess :slight_smile: let me try if that works. I still dont have a strong understanding on all the pointer types and refs of rust

Neither have I, but apparently enough understanding by now.

You do sound confident here... I'm not entirely sure that user.credentials.cloned().map(|v| would clone the whole credential, but I guess so. 28 years after I wrote a thesis on partial evaluation, you'd think a compiler would figure out to not bother wasting effort on data that doesn't matter, but I've been let down before in my expectations of Rust.

In your example Creds is composed of 2 &str (4 usize), cloning it is almost free.