Search code examples
structrustiteratorclosuresmap-function

Map a Vec of structures to another Vec of structure in Rust without cloning


I use a library that has the following structure:

struct KeyValue1 {
    key: Vec<u8>,
    value: Vec<u8>,
}

fn get() -> Vec<KeyValue1> { /* ... */ }

I need to convert this vector to an almost similar vector that has the following structure:

struct KeyValue2 {
    key: Vec<u8>,
    value: Vec<u8>,
}

To be able to convert from one vector to another, I currently use the following code:

let convertedItems = items.iter().map(|kv| -> KeyValue2{
  key: key.clone(),
  value: value.clone()
}).collect()

Although this works, it clones both vectors which is inefficient. I don't need the original items vector anymore, so I want to transfer ownership from KeyValue1 to KeyValue2, but I haven't found a way to do this.


Solution

  • Use into_iter() instead of iter() on the items vector if you don't need it after the conversion:

    struct KeyValue1 {
        key: Vec<u8>,
        value: Vec<u8>,
    }
    
    struct KeyValue2 {
        key: Vec<u8>,
        value: Vec<u8>,
    }
    
    fn map_key_values(items: Vec<KeyValue1>) -> Vec<KeyValue2> {
        items
            .into_iter()
            .map(|kv| KeyValue2 {
                key: kv.key,
                value: kv.value,
            })
            .collect()
    }
    

    playground