check size of a vector in rust

To check the size of a Vector in Rust, you can use the len() method of the Vec struct. This returns the number of elements in the Vector.

main.rs
let vec = vec![1, 2, 3, 4, 5];
let size = vec.len();
println!("Size of Vector: {}", size);
91 chars
4 lines

This will output:

main.rs
Size of Vector: 5
18 chars
2 lines

You can also use the capacity() method to get the total amount of memory that has been allocated for the Vector:

main.rs
let vec = vec![1, 2, 3, 4, 5];
let capacity = vec.capacity();
println!("Capacity of Vector: {}", capacity);
108 chars
4 lines

This will output:

main.rs
Capacity of Vector: 5
22 chars
2 lines

Note that the capacity() method returns the number of elements that can be stored in the allocated space without requiring additional memory allocation.

related categories

gistlibby LogSnag