std-method

HashMap::contains_key

Test whether a key exists without retrieving or consuming its value. A borrowed query must follow the same equality and hashing rules as the stored key. Expected stdout (not executed): true false Common mistake: Checking contains_key and then get when a single get would suffice.

Formal Syntax & Structure

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

Working Example

Example Snippetrust
fn main() {    use std::collections::HashMap;    let settings = HashMap::from([("port", 8080)]);    println!("{} {}", settings.contains_key("port"), settings.contains_key("timeout"));}
Rust Reference