📜  泛型类型的 rust vec (1)

📅  最后修改于: 2023-12-03 15:11:04.788000             🧑  作者: Mango

Rust Vec with Generic Types

In Rust, Vec is a widely used data structure that stores elements in contiguous memory locations. It is one of the most common types of collections in Rust.

Which types can be stored in a Vec?

Vec is a generic type that can store any type that implements the Clone trait. This includes all primitive data types such as integers, booleans, and characters, as well as Rust structs, enums, and custom types.

To create a vector of a specific data type, you can specify the type inside the angle brackets < >:

let numbers: Vec<i32> = vec![1, 2, 3];
let letters: Vec<char> = vec!['a', 'b', 'c'];
Creating a new Vec

To create a new vector, you can use the Vec::new() method or the vec! macro:

let mut my_vec = Vec::new(); // create an empty vector
my_vec.push(42); // add a value to the end of the vector
let my_vec = vec![1, 2, 3]; // create a vector with initial values
Accessing elements in a Vec

You can access elements in a vector using square brackets [], which returns an immutable reference to the element:

let my_vec = vec![1, 2, 3];
let first_element = my_vec[0];

To mutate an element, you can use the mut keyword to get a mutable reference:

let mut my_vec = vec![1, 2, 3];
my_vec[1] = 42;
Iterating through a Vec

You can use a for loop to iterate over all elements in a vector:

let my_vec = vec![1, 2, 3];
for element in my_vec {
    println!("{}", element);
}

You can also use the iter() method to create an iterator over the vector's elements:

let my_vec = vec![1, 2, 3];
for element in my_vec.iter() {
    println!("{}", element);
}
Conclusion

The Rust Vec type is a powerful, flexible, and efficient data structure for storing collections of data. Its generic type allows it to be used with any data type that implements the Clone trait, making it highly versatile in a wide range of applications.