Collections are data structures for storing multiple values.
stack
while collections are stored on the heap
vector
: collection of numbersstring
: collection of charactershash map
: collection of key-value pairsThis program will not compile
enum
String
s?String
vs str
String
str
More info: Rust User’s forum – Stack Overflow
String
sVec<u8>
.chars()
You can create a hash map with new
and add values with .insert
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Red"), 10);
scores.insert(String::from("Blue"), 20);
let blue_team = String::from("Blue");
let blue_score = scores.get(&blue_team).copied().unwrap_or(0); // 20
get
returns an Option<&V>
copied
returns an Option<i32>
instead of Option<&i32>
unwrap_or
returns 0
if there is no entry for "Blue"
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Red"), 10);
scores.insert(String::from("Blue"), 20);
for (key, value) in &scores {
println!("{key}: {value}");
} // Red: 10, Blue: 20
Order is arbitrary