If you remember, array is a fixed-size list of elements, of same data type. Even with mut, its element count can not be changed. A vector is kind of a re-sizable array but all elements must be in the same type.
⭐️ It’s a generic type, written as Vec<T> . T can have any type, ex. The type of a Vec of i32s is Vec<i32>. Also Vectors always allocate their data in dynamically allocated heap.
Create empty vector
letmut a =Vec::new(); //1.with new() keywordletmut b =vec![]; //2.using the vec! macro
//Accessing and changing exsisting dataletmut c =vec![5, 4, 3, 2, 1];c[0] =1;c[1] =2;//c[6] = 2; can't assign values this way, index out of boundsprintln!("{:?}", c); //[1, 2, 3, 2, 1]//push and popletmut d:Vec<i32> =Vec::new();d.push(1); //[1] : Add an element to the endd.push(2); //[1, 2]d.pop(); //[1] : : Remove an element from the end// 🔎 Capacity and reallocationletmut e:Vec<i32> =Vec::with_capacity(10);println!("Length: {}, Capacity : {}", e.len(), e.capacity()); //Length: 0, Capacity : 10// These are all done without reallocating...for i in0..10 { e.push(i);}// ...but this may make the vector reallocatee.push(11);
⭐️ Mainly a vector represent 3 things,
a pointer to the data
No of elements currently have(length)
capacity (Amount of space allocated for any future elements).
If the length of a vector exceeds its capacity, its capacity will be increased automatically. But its elements will be reallocated(which can be slow). So always use Vec::with_capacity whenever it’s possible.
💡 String data type is a UTF-8 encoded vector. But you can not index into a String because of encoding.
💯 Vectors can be used with iterators in three ways,
letmut v =vec![1, 2, 3, 4, 5];for i in&v {println!("A reference to {}", i);}for i in&mut v {println!("A mutable reference to {}", i);}for i in v {println!("Take ownership of the vector and its element {}", i);}