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 Maybe.map from elm language.

let user = User{
	username:""
	credentials:Some(Creds{
		name:"value",
		another:"anotheValue",
	}),
}

let maybeName = user.credentials.map(|v|v.name.clone())
let maybeAnother = user.credentials.map(|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|v.name.clone())?

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|v.name) 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.