30.1.1Vector¶
Accessing a vector’s element with get() is safer than with the
indexing operator ([]). get() returns an Option<T> and uses the
None when the index is out of range:
let v = vec![1, 2, 3];
let elem = v.get(4);
match elem {
Some(elem) => println!("Value is {elem}"),
None => println!("Error, index is out of range."),
}Error: The variable `elem` contains a reference with a non-static lifetime so
can't be persisted. You can prevent this error by making sure that the
variable goes out of scope - i.e. wrapping the code in {}.30.1.2Map¶
Like the Vec, maps can be accessed either with the index operator
([]) or the get() method.
Let us construct a map:
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert("Paul", 15);
scores.insert("John", 20);Couldn't automatically determine type of variable `scores`.
Please give it an explicit type.The index operator will return the value directly:
scores["Paul"]The get() method will return an Option<T>:
scores.get("Paul")However if the key is unknown the index operator will panic:
let mut scores = std::collections::HashMap::new();
scores.insert("Paul", 15);
scores["John"]