Collections
Vectors
To store expandable list of same type of elements, use vec
let elements: Vec<i32> = Vec::new();
Vectors only store same types of elements
Consider below code
let mut v = vec![1, 3, 4];
let first_element = &v[0]; // immutable borrow
v.push(7); //error //mutable
println!("{}", first_element); //immable borrow value accessing
Error occurs at line 4. Because we are doing a mutable borrow after immutably referencing the value at line 2. Even though it's a reference, there will still be error because internally, Rust might deallocate memory and allocate to a new memory. If this happens first_element might be referencing to deallocated memory.
To store different kind of elements inside vector, then use enums!
fn store_different_elements() {
let mut diff_value_vec = vec![Store::IntValue(2),
Store::StringValue(String::from("Helo"))];
diff_value_vec.push(Store::IntValue(9));
//diff_value_vec.push(10);
}
enum Store {
IntValue(u32),
StringValue(String),
}
Rust needs to know what kind of values are stored inside vector at compile time so that it would know how memory is needed for allocation in the heap
Last updated
Was this helpful?