std-method

HashMap::get

Look up a value by a shared reference to a compatible key representation. For a map with String keys, a str query avoids building another String. A missing key yields None. Expected stdout (not executed): Some(4) None Common mistake: Using indexing for uncertain keys; indexing panics when absent.

Formal Syntax & Structure

rust syntaxrust
pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> where K: Borrow<Q>, Q: Hash + Eq

Working Example

Example Snippetrust
fn main() {    use std::collections::HashMap;    let stock = HashMap::from([(String::from("pen"), 4)]);    println!("{:?} {:?}", stock.get("pen"), stock.get("ink"));}
Rust Reference