Skip to content
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

new idiom: mem::replace #31

Merged
merged 2 commits into from
Oct 8, 2016
Merged

Conversation

llogiq
Copy link
Contributor

@llogiq llogiq commented Oct 8, 2016

This is something I recently found to be quite useful.


## Advantages

Look ma, no allocation! Also you may feel like Indiana Jones while doing it.
Copy link
Collaborator

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. 😎

Copy link
Contributor Author

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 => {
Copy link
Collaborator

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.

Copy link
Contributor Author

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 } }
Copy link
Collaborator

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.

Copy link
Contributor Author

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.

@cbreeden
Copy link
Collaborator

cbreeden commented Oct 8, 2016

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.

@llogiq
Copy link
Contributor Author

llogiq commented Oct 8, 2016

@cbreeden that'd be great.

@cbreeden cbreeden merged commit 9b289ac into rust-unofficial:master Oct 8, 2016
@llogiq llogiq deleted the mem-replace branch October 8, 2016 17:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants