-1

I want to map entity from one Vec(this entity list search from database) into another Vec(this response entity list return to frontend) in rust, this is my code:

fn main() {
    let musics:Vec<Music> = Vec::new();
    for x in 0..10 {
        let filtered_music:Vec<Music> = musics.into_iter()
            .filter(|item| item.source_id == "1")
            .collect();
        let resp = MusicRes{
            music: take(filtered_music, 0).unwrap()
        };
    }
}

fn take<T>(mut vec: Vec<T>, index: usize) -> Option<T> {
    if index < vec.len() {
        Some(vec.swap_remove(index))
    } else {
        None
    }
}

pub struct Music {
    pub id: i64,
    pub name: String,
    pub artists: String,
    pub album_id: i64,
    pub publishtime: i64,
    pub status: i32,
    pub duration: i32,
    pub source_id: String,
    pub source: i32,
    pub created_time: i64,
    pub updated_time:i64,
    pub album: String,
    pub fetched_download_url: i32
}

pub struct MusicRes {
    pub music:Music
}

this code give me tips that musics was moved. I could change the musics to &musics, but the returned response need to Music. How to handle this situation properly?

Dolphin
  • 29,069
  • 61
  • 260
  • 539
  • How is this different from your [previous question](https://stackoverflow.com/questions/70410216/get-element-from-vec-that-tell-me-could-not-move-in-rust)? – mkrieger1 Dec 19 '21 at 11:07

1 Answers1

1

I'm not exactly sure what your requirements are, ie. what's the point of the 0..10 then taking the 0th element, but you could do something like this:

let musics: Vec<_> = musics
    .into_iter()
    .take(10)
    .filter(|m| m.source_id == "1")
    .map(|m| MusicRes { music: m })
    .collect();
Riwen
  • 4,734
  • 2
  • 19
  • 31