Day 13m: Vector Interoperability with Other Collections

Venkat Annangi
Venkat Annangi
08/10/2024 02:39 1 min read 35 views
#rust-vectors #rust #108 days of rust

Day 13m: Vector Interoperability with Other Collections

Introduction

Vectors are highly interoperable with other Rust collections. In this session, we’ll explore how to convert vectors to and from arrays, hash maps, and other collection types.

Converting Vectors to Arrays

You can convert a vector into an array if the vector’s size is known at compile time.

fn main() {

    let numbers = vec![1, 2, 3, 4];

    let array: [i32; 4] = match numbers.try_into() {

        Ok(arr) => arr,

        Err(_) => panic!("Incorrect length!"),

    };

    println!("{:?}", array);

}

Converting Vectors to HashMaps

You can convert a vector of key-value pairs into a HashMap.

use std::collections::HashMap;



fn main() {

    let pairs = vec![("one", 1), ("two", 2), ("three", 3)];

    let map: HashMap<_, _> = pairs.into_iter().collect();

    println!("{:?}", map);

}

Conclusion

Understanding how vectors can interoperate with other collections such as arrays and hash maps is key to using Rust’s standard library effectively.

Comments