If I have a vector of references, I can do this:
references.into_iter().map(|x| *x).collect::<Vec<_>>();
Is there a short-hand that does this? This would be easy to answer with hoogle-like search engine but I can't find one for Rust.
Relatedly, I'd be also curious if there is a shorthand for the opposite operation:
objects.iter().collect::<Vec<_>>()
There's probably no operation exactly like the one you want. You can
clone()
the vector, but that will just give you another vector with the same references. If you want to transform the vector elements, you're supposed to do that with the iterator interface because, after all, you might not want to save the results into a vector. And if you do want the results in a vector - well, that's whatcollect()
is for.Having said the above, here are some ways to make it shorter:
map(|x| *x)
withcopied()
.::<Vec<_>>
"turbofish" because the function will have the return type spelled out, and Rust will be able to infer it.return
if it's the last expression in your function.Combining the above, you can replace
return references.into_iter().map(|x| *x).collect::<Vec<_>>();
withreferences.into_iter().copied().collect()
, which is visibly shorter, though perhaps not exactly what you were after.