Changing a nested reference into a reference
I have a situation where I want to create an iterator over &str. When I want to chain some strs which are stored in an array, the item type of the iterator is &&str, which is incompatible with &str. I found a way of solving it, but I was wondering if there is something I'm missing which might make it more elegant. Any suggestions? (see example below)
Further I was wondering if one could generally turn any nested reference to a reference. To rephrase it a bit; can a &&T always be safely turned into a &T?
let xs = &["b", "c"];
// I wish this would compile, but it gives a error regarding the
// item-types not matching: `&&str` is not equal to `&str`.
//once("a").chain(xs).for_each(|c| println!("{}", c));
// The solution I am currently using. `clippy` suggests using `.cloned`, however
// then it looks like the iterator does some "expensive" cloning.
once("a")
.chain(xs.iter().map(|s| *s))
.for_each(|c| println!("{}", c));
Posted Feb 1, 2019, 9:58 PM UTC
16
Your second version is basically the way to do it, but
map(|s| *s)is actually spelledcloned(). It's a somewhat unfortunate name because what's being cloned is the reference, not the contents, but it makes sense if you really grok pointers.For that reason,
&&Tcan always become&Tby virtue of the Clone and Copy impls on&Tfor allT. If you check the signature of Clone::clone() and fill in&T2forTyou see it is&&T2 -> &T2. Copy can be thought of as having the same "signature" as Clone in the sense that Copy is just Clone elision.Thank you for an answer!
It's not to be picky, but
map(|s| *s)requiresCopywhilecloned()only requiresClone, so they are a bit different in the sense that the former will only compile if the type is "trivial" to clone, hence it might protect us in the future if we change some other requirements in the code that makes the iterator an iterator over owned values.I see your point regarding "if you really grok pointers" it will be easy to see that clone on pointers are cheap operations. It is really handy that pointers implement clone instead of it being a different member function or trait, but I do wish that perhaps it could have been a better name for it. I think this is the reason a lot of people rather use
Arc::clone(&ptr)instead of justptr.clone(), because the former shows that it's a cheap operation. I wish there was acopymember function of theCopytrait which would delegate toclone, because then one could be sure thatdata.copy()is a cheap operation whiledata.clone()is most likely an expensive operation.There was talk about adding a
.copied()method (for Copy types) to Iterator alongside the.cloned()method. This might help a little bit to make it clear what is a cheap operation.Edit: https://github.com/rust-lang/rust/issues/57127
I will definitely change to
.copiedif it gets stabilized. Thank you for the link!Why wait? You can implement this using an extension trait. (
IteratorExt)