Closed liamzdenek closed 3 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.
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.
I have a few ideas for examples:
.cloned()
) which is actually OK in many cases (unless you can consume the collection while iterating, which should be preferred)entry(_.clone())
– there's an RFC to get rid of that.Hope that helps.
Anything left for this?
@liamzdenek any updates on this?
Closing due to inactivity. Further additions to the PR can be made in #110.
I feel like this write-up could be improved, but I'm not exactly sure how -- recommendations and modifications are welcome.