📜  rust vec length - Rust (1)

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

Rust Vec Length

In Rust, Vec is a dynamically resizable array. It is one of the most commonly used data structures in Rust programming. One of the most important properties of Vec is its length, which represents the number of elements currently stored in the Vec.

Retrieving the Length of a Vec

To get the length of a Vec, we can use the len() method, which returns the number of elements in the Vec.

let vec = vec![1, 2, 3, 4, 5];
println!("The length of the vec is {}.", vec.len());

Output:

The length of the vec is 5.
Changing the Length of a Vec

The length of a Vec can be changed using various methods, such as push(), which adds a new element to the end of the Vec, and pop(), which removes the last element from the Vec. These methods automatically adjust the length of the Vec.

let mut vec = vec![1, 2, 3];
vec.push(4);
println!("After push, the length of the vec is {}.", vec.len()); // Output: After push, the length of the vec is 4.
vec.pop();
println!("After pop, the length of the vec is {}.", vec.len()); // Output: After pop, the length of the vec is 3.

Besides automatic adjustment, we can also manually set the length of a Vec using the truncate() method, which removes all elements after the specified index, and resize() method, which adds or removes elements to match the specified length.

let mut vec = vec![1, 2, 3];
vec.truncate(1);
println!("After truncate, the length of the vec is {}.", vec.len()); // Output: After truncate, the length of the vec is 1.
vec.resize(3, 0);
println!("After resize, the length of the vec is {}.", vec.len()); // Output: After resize, the length of the vec is 3.
Conclusion

The length of a Vec is an important property that helps us manage the elements stored in the Vec. With the help of various methods provided by Rust, we can easily retrieve, change, and set the length of a Vec.