Vec<T>
allows you to store more than one value in a single data structure that puts all the values next to each other in memory. Vectors can only store values of the same type.
let v: Vec<i32> = Vec::new(); // empty vector
let v = vec![1,2,3]; // initialize with array
let v = vec![1, 2, 3, 4, 5];
// retrieving elements
let third: &i32 = &v[2];
let third: Option<&i32> = v.get(2); // can use match later
// if vector is mutable, retrieval has to be mutable too
let mut v = Vec::new();
v.push(1);
v.push(1);
v.push(4);
let mut first: &i32 = &v[0];
// iterating through vector
for i in &v {
println!("{i}"}
}
// to mutate the vector
for i in &mut v {
*i += 50;
}
If we want to store more than one type in vector, we could utilize enum
enum SpreadsheetCell {
Int(i32),
Float(f64),
Text(String),
}
let row = vec![
SpreadsheetCell::Int(3),
SpreadsheetCell::Text(String::from("blue")),
SpreadsheetCell::Float(10.12),
];
String literal(str
) is different from the String
type, which is provided by Rust’s standard library rather than coded into the core language
let mut s = String::new();
let s = "hello".to_string();
let mut s = String::from("hello");
// to change
s.push_str(" world");
let s2 = '!';
s1.push_str(s2) // s1 -> hello world!
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used
Note that Rust does not support string indexing since UTF8 chars might have different length in bytes. However, we could specify a range of stirng to access
The type HashMap<K, V>
stores a mapping of keys of type K
to values of type V
using a hashing function.
use::std::collections::HashMap;
let mut scores = HashMap::new<>;
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
for (key, value) in &scores {
println!("{key}: {value}");
}
print!(scores.entry(String::from("Yellow")))
// if didn't find, insert the new value and return that ref
print!(scores.entry(String::from("Black")).or_insert(114))