rust-unofficial / patterns

A catalogue of Rust design patterns, anti-patterns and idioms
https://rust-unofficial.github.io/patterns/
Mozilla Public License 2.0
8.11k stars 375 forks source link

Adding 'clone to satisfy the borrow checker' anti-pattern #23

Closed liamzdenek closed 3 years ago

liamzdenek commented 8 years ago

I feel like this write-up could be improved, but I'm not exactly sure how -- recommendations and modifications are welcome.

cbreeden commented 8 years ago

I like your motivation and description. I think we can make improve this section quite a bit if we put a little more polish into the example, and add examples that shows how you can avoid the problems. I'll play around with a few ideas and get back to you.

cbreeden commented 8 years ago

So I tried to think of some good examples, what do you think about this one

// Our personal key-value storage for names and ages
let mut vec = vec![("Bob".to_string(), 17), ("Stacy".to_string(), 21)];
let new_pair = ("Ferris".to_string(), 13);

// check for duplicates
let (ref key, _) = new_pair;
if vec.iter().map(|&(ref k, _)| k).find(|&k| k == key).is_none() {
    // Can't move since new_pair is being referenced still!
    vec.push(new_pair);
}

println!("{:?}", vec);

I could imagine someone trying to add a .clone() to the new_pair in vec.push(new_pair);. A lot of times these problems can be solved by properly managing their lifetimes -- in this case just adding k == &new_pair.0. In other cases, closing a mutable borrow scope in brackets. I don't know if this is the best example, just throwing it out there.

llogiq commented 7 years ago

I have a few ideas for examples:

Hope that helps.

pickfire commented 4 years ago

Anything left for this?

simonsan commented 3 years ago

@liamzdenek any updates on this?

simonsan commented 3 years ago

Closing due to inactivity. Further additions to the PR can be made in #110.