Common Collections (Vector and Strings) in Rust [Notes]
Chapter 8: Common Collections These are my notes from the chapter-8 of rust book. Please scroll down to the bottom (Note) section if you are curious about what this is. 8.1: Storing Lists of Values with Vectors Vec<T> collection type discussed, aka vector: * By default contiguous. * All values should be of same type. // Creation let v: Vec<i32> = Vec::new(); // vec! macro for convenience // default integer type is i32 let v = vec![1, 2, 3]; // Modifying let mut v = Vec::new(); // Rust infers the type from the elements pushed here v.push(5); v.push(6); // ... // Dropping // a vector is freed, when it goes out of scope { let v = vec![1, 2, 3, 4]; // ... } // <-- v goes out of scope here, and hence memory is freed as well // Reading Elements of Vectors let v = vec![1, 2, 3, 4, 5]; // First way: let third: &i32 = &v[2]; println!("The third element is: {}", third); // Second way: match v.get(2) { Some(num) => println!("The third element is: {}", num), None => println!("There is no third element."), } .get(&index) method allows you to handle out of range errors. ...