Easier way to move elements out from an owned collection?

#1

For example, consider the following function that take ownership of a String vector, and return a String vector directly:

fn consume_produce(x : Vec<String>) -> Vec<String> {
    x.iter().map(|x| x.to_owned()).collect::<Vec<String>>()
}

Imagine that we can do some other stuff in the map function or after the map. I found that I have to call to_owned() explicitly. Is there a more conventional or easier way to do something like this? Also as an example, why this doesn’t work:

fn consume_produce(x : Vec<String>) -> Vec<String> {
    x.iter().map( |x| *x).collect::<Vec<String>>()
}
0 Likes

#2

Use .into_iter() instead of .iter() to get owned elements without making a copy of them.

.iter() gives you a borrow, and if you’ve borrowed something, you can’t take ownership of it.

*x happens to work on borrowed Copy types, because the impossibility of taking ownership of borrowed value is solved by making a copy instead.

But String is not copy, so it won’t be copied, so *x means you’re trying to steal a borrowed reference.

2 Likes

#3

It seems that I had a misunderstanding of *. Thanks for helping me out!

0 Likes