Cody Casterline ๐Ÿณ๏ธโ€๐ŸŒˆ is a user on mastodon.social. You can follow them or interact with them if you have an account anywhere in the fediverse. If you don't, you can sign up here.

#Rustlang won't let you cut the branch you're sitting on.

Sometimes you need to change a complex struct or enum based on its contents. However, you can't do this inside a `match` that takes references, because the references inside the `match` keep a "lock" on the whole object and prevent it from being replaced.

The solution is to use `match` only to check the condition, and perform replacement in a separate step after the `match`.

It's better explained with code:

play.rust-lang.org/?gist=f7616

@NfNitLoop Your code doesn't compile with `&mut Some(5)`, and difficulty of working with &Option (rather than freely movable owned Option) was the whole point of the tip.

@NfNitLoop Eh, my original example was too simplified to show it's about unmovable content, i.e. when you have a reference to a large struct/vec or something uncloneable like a file handle.

This time you're dodging use of references by copying the contents instead.

play.rust-lang.org/?gist=43aa4

@kornel aaaah. Yeah, in that case, you can simplify things by first take()ing the value. If you can't copy it, move it instead! :)