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.
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.
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);
}
}
Rust Program to show dynamic size increase
use std::io::{stdin};
fn main() {
let mut vec:Vec=Vec::new();
loop { // Add to the Vector as along as "break" is received
let mut input =String::new();
// Read Input from Command Line
stdin().read_line(&mut input).ok().expect("Failed");
//let inp=input;
// Strip \r\n from input
let inp=input.replace("\r\n", "");
if inp == "break"{ //Break the loop
break;
}
if inp == "info"{
println!("\n---------------------------");
// Vector Size automatically increases
println!("Vector has capcity of: {}",vec.capacity());
println!("Number of Values in Vector: {}",vec.len());
println!("First Item in Vector:{:?}",vec.first());
println!("Last Item in Vector:{:?}",vec.last());
println!("---------------------------\n");
continue;
}
vec.push(inp); // Add Value to the Vector/dynamic Array
println!("Vector Length:{}",vec.len());
println!("Vector Values {:?}",vec);
}
}