-
Notifications
You must be signed in to change notification settings - Fork 383
new idiom: mem::replace #31
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
|
||
## Advantages | ||
|
||
Look ma, no allocation! Also you may feel like Indiana Jones while doing it. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I still remember the day I learned mem::replace
, and this is exactly how I felt. 😎
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Welcome to the club... 😎
// we could just take a reference to `name` and clone that, but why pay an | ||
// extra allocation for something we already have? | ||
let have_name = match *e { | ||
MyEnum::A(ref mut name, x) if x == 0 => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
MyEnum::A{ ref mut name, x }
I believe.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks, fixed.
_ => None | ||
}; | ||
// the mutable borrow ends here, so we can change `e` | ||
if let Some(name) = have_name { *e = MyEnum::B { name } } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
MyEnum::B { name: name }
at least until the field init shorthand RFC stabilizes if accepted.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
True that. I appear to live in the future from time to time.
Indeed, this can be quite useful. I like the example a lot. Do you mind adding a link to the table of contents? I can add a note to the clone to satisfy the borrow checker PR, or a new GH issue to remind us to update the relevant links here when that anti-pattern is finished. |
@cbreeden that'd be great. |
This is something I recently found to be quite useful.