I passed a vec parameter into function in rust like this:
pub fn songs(playlist_records: Vec<QueryFavorites>) -> Vec<MusicResponse> {
}
first step I get the ids from playlist_records
to execute a query, this is the code:
let ids: Vec<String> = playlist_records
.into_iter()
.map(|item| item.source_id.to_string())
.collect();
when I use the playlist_records
second time to fetch the field after get the query result:
for query_song in &results {
let favTime: Vec<QueryFavorites> = playlist_records
.into_iter()
.filter(|item| item.source_id == query_song.source_id)
.collect();
}
it tell me the playlist_records
was moved. This is the message:
`playlist_records` moved due to this method call, in previous iteration of loop
I tried to borrow the playlist_records
like this:
let ids: Vec<String> = &playlist_records
.into_iter()
.map(|item| item.source_id.to_string())
.collect();
seems did not work, what should I do to reuse the playlist_records
?
CodePudding user response:
Change into_iter
to use iter
, since into_iter
consumes the collection while iter
iterates by reference and doesn't consume, see more about the difference here:
let ids: Vec<String> = playlist_records
.iter()
.map(|item| item.source_id.to_string())
.collect();
let favTime: Vec<&QueryFavorites> = playlist_records
.iter()
.filter(|item| item.source_id == "someid")
.collect();
which however means your favTime
will be of Vec<&QueryFavorites>
type if that's fine with you. Otherwise, you can always clone the iterator.
let favTime: Vec<QueryFavorites> = playlist_records
.iter()
.cloned()
.filter(|item| item.source_id == "someid")
.collect();