<tutorialjinni.com/>

Rust Dynamic Array - Vectors

Posted Under: Programming, Rust, Tutorials on Sep 30, 2021
Rust Dynamic Array - Vectors
Arrays in Rust are not dynamic, array size and type of data it will hold need to be defined before compilation. Vector are the dynamic arrays in Rust. Vector can hold a growing number of the same data type elements. Vector initialization must require a data type annotation or at least one element entry in it, so that compiler knows which data type this will holds.
let vec=Vec::new(); //this will throw error cannot infer type for type parameter `T`
Proper way to initialize vector
fn main() {
    let mut vec=Vec::new();
    vec.push(2);
}
or
let mut vec: Vec=Vec::new();

Rust Vector Add Element

To add an element is Vector push() method is used.
fn main() {
    let mut primes=Vec::new();
    primes.push(2);
    primes.push(5);
    primes.push(7);
}

Rust Vector Length

len() methor tells total number of elements in a Vector.
fn main() {
    let mut primes=Vec::new();
    primes.push(2);
    primes.push(5);
    println!("Vector Length:{}",primes.len());
}

Get Values from Vector

There two ways of getting values from a Vector pop() and get(). pop() returns the last elemnets and removes it from the vector, however get() returns the elemets at spcified index only.
fn main() {
    let mut primes=Vec::new();
    primes.push(2);primes.push(5);
    primes.push(7);primes.push(11);
    println!("Vector Length Before pop() :{}",primes.len());
    println!("poping :{:?}",primes.pop().unwrap()); // unwarp is used to get the original value
    println!("Vector Length After pop() :{}",primes.len());
    println!("get element at index 2 :{:?}",primes.get(2).unwrap());
    println!("Vector Length:{}",primes.len());
}
//output 
//Vector Length Before pop() :4
//poping :11
//Vector Length After pop() :3
//get element at index 2 :7   
//Vector Length:3

Rust sort Vector

To sort values in the vector sort() function is used.
fn main() {
    let mut alpha=Vec::new();
    alpha.push("E");alpha.push("F");
    alpha.push("D");alpha.push("A");
    alpha.push("C");alpha.push("B");
    println!("Before Sorting{:?}",alpha);
    alpha.sort();
    println!("After Sorting{:?}",alpha);
}
//output
//Before Sorting["E", "F", "D", "A", "C", "B"]
//After Sorting["A", "B", "C", "D", "E", "F"]

Rust Vector Iteration

To iterate all values in a vector a simple for loop will do the job.
fn main() {
    let mut fruits=Vec::new();
    fruits.push("Oranges");fruits.push("Banana");
    fruits.push("Apples");fruits.push("Tomato");
    for i in &fruits{
        println!("{}",i);
    }
}
© Tutorial Jinni


imgae