Rust Programming: Storing Lists of Values with Vectors

0

Vectors are a common collection type in Rust that can be used to store lists of values. They are dynamic, meaning that they can grow and shrink as needed. Vectors are also efficient, as they store all of their elements contiguously in memory.

To create a new vector, you can use the Vec::new() function. For example, the following code creates a new vector that can store integers:

Rust
let v: Vec<i32> = Vec::new();

You can then add elements to the vector using the push() method. For example, the following code adds the numbers 1, 2, and 3 to the vector:

Rust
v.push(1);
v.push(2);
v.push(3);

You can also access elements of a vector using the [] operator. For example, the following code prints the second element of the vector:

Rust
println!("{}", v[1]);

Vectors are a powerful tool for storing lists of values in Rust. They are efficient, dynamic, and easy to use.

Here are some examples of how vectors can be used in Rust:

  • To store a list of scores in a video game.
  • To store the items in a shopping cart.
  • To store the lines of text in a file.
  • To store the vertices of a 3D model.

Vectors are a versatile and useful collection type in Rust.

Post a Comment

0Comments
Post a Comment (0)