Question:
Vector in a HashMap [duplicate]

I know how to use, String I know how to use, Vector But I am facing issue to use HashMap

```
#[derive(Serialize)]
pub struct TestStructs {
    pub ttStrngg: String,
    pub ttVctorr: Vec<String>,
    pub ttHshMpp: HashMap<String, Vec<String>>,
}
```

Here is what I am trying

Don't have any issues with String
```
ttStrngg: "Stringgg".to_string()
```

Don't have any issues with Vector
```
ttVctorr: vec!["VecStr1".to_string(), "VecStr2".to_string()]
```

But do have an issue with HashMap
```
ttHshMpp: "HMK1".to_string(), vec!["K1V1".to_string(), "K1V2".to_string()]
```

I've shared what I tried and now looking for that missing thing in HashMap

Here is the Rust Playground link to try your own

And here is the error

```
    Compiling playground v0.0.1 (/playground)
error: expected one of `,`, `:`, or `}`, found `!`
 --> src/main.rs:9:46
  |
6 |     let ttStrctts = TestStructs {
  |                     ----------- while parsing this struct
...
9 |             ttHshMpp: "HMK1".to_string(), vec!["K1V1".to_string(), "K1V2".to_string()]
  |                                           ---^ expected one of `,`, `:`, or `}`
  |                                           |
  |                                           while parsing this struct field

error[E0308]: mismatched types
 --> src/main.rs:9:23
  |
9 |             ttHshMpp: "HMK1".to_string(), vec!["K1V1".to_string(), "K1V2".to_string()]
  |                       ^^^^^^^^^^^^^^^^^^ expected `HashMap<String, Vec<String>>`, found `String`
  |
  = note: expected struct `HashMap<std::string::String, Vec<std::string::String>>`
             found struct `std::string::String`
```

Explanation: The programmer knows less on `HashMap`, especially the use and implementation of pair `(k, v)` and array `[]` of `HashMap`. The relative docs are required.

](../../std/index.html)

[ ![logo](../../static.files/rust-logo-151179464ae7ed46.svg)
](../../std/index.html)

##  [ std ](../../std/index.html) 1.80.1

(3f5fd8dd4 2024-08-06)

##  HashMap

###  Methods

  * capacity
  * clear
  * contains_key
  * drain
  * entry
  * extract_if
  * get
  * get_key_value
  * get_many_mut
  * get_many_unchecked_mut
  * get_mut
  * hasher
  * insert
  * into_keys
  * into_values
  * is_empty
  * iter
  * iter_mut
  * keys
  * len
  * new
  * raw_entry
  * raw_entry_mut
  * remove
  * remove_entry
  * reserve
  * retain
  * shrink_to
  * shrink_to_fit
  * try_insert
  * try_reserve
  * values
  * values_mut
  * with_capacity
  * with_capacity_and_hasher
  * with_hasher

###  Trait Implementations

  * Clone
  * Debug
  * Default
  * Eq
  * Extend<(&'a K, &'a V)>
  * Extend<(K, V)>
  * From<[(K, V); N]>
  * FromIterator<(K, V)>
  * Index<&Q>
  * IntoIterator
  * IntoIterator
  * IntoIterator
  * PartialEq
  * UnwindSafe

###  Auto Trait Implementations

  * Freeze
  * RefUnwindSafe
  * Send
  * Sync
  * Unpin

###  Blanket Implementations

  * Any
  * Borrow<T>
  * BorrowMut<T>
  * From<T>
  * Into<U>
  * ToOwned
  * TryFrom<U>
  * TryInto<U>

##  [ In std::collections ](index.html)

#  Struct [ std ](../index.html) ::  [ collections ](index.html) ::  HashMap
Copy item path

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#213-215) Â·  [
−  ]

    pub struct HashMap<K, V, S = [RandomState](hash_map/struct.RandomState.html "struct std::collections::hash_map::RandomState")> { /* private fields */ }

Expand description

A [ hash map ](index.html#use-a-hashmap-when "mod std::collections")
implemented with quadratic probing and SIMD lookup.

By default, ` HashMap ` uses a hashing algorithm selected to provide
resistance against HashDoS attacks. The algorithm is randomly seeded, and a
reasonable best-effort is made to generate this seed from a high quality,
secure source of randomness provided by the host without blocking the program.
Because of this, the randomness of the seed depends on the output quality of
the systemâs random number coroutine when the seed is created. In
particular, seeds generated when the systemâs entropy pool is abnormally low
such as during system boot may be of a lower quality.

The default hashing algorithm is currently SipHash 1-3, though this is subject
to change at any point in the future. While its performance is very
competitive for medium sized keys, other hashing algorithms will outperform it
for small keys such as integers as well as large keys such as long strings,
though those algorithms will typically _not_ protect against attacks such as
HashDoS.

The hashing algorithm can be replaced on a per- ` HashMap ` basis using the [
` default ` ](../default/trait.Default.html#tymethod.default "associated
function std::default::Default::default") , [ ` with_hasher `
](hash_map/struct.HashMap.html#method.with_hasher "associated function
std::collections::hash_map::HashMap::with_hasher") , and [ `
with_capacity_and_hasher `
](hash_map/struct.HashMap.html#method.with_capacity_and_hasher "associated
function std::collections::hash_map::HashMap::with_capacity_and_hasher")
methods. There are many alternative [ hashing algorithms available on
crates.io ](https://crates.io/keywords/hasher) .

It is required that the keys implement the [ ` Eq ` ](../cmp/trait.Eq.html
"trait std::cmp::Eq") and [ ` Hash ` ](../hash/trait.Hash.html "trait
std::hash::Hash") traits, although this can frequently be achieved by using `
#[derive(PartialEq, Eq, Hash)] ` . If you implement these yourself, it is
important that the following property holds:

    k1 == k2 -> hash(k1) == hash(k2)

In other words, if two keys are equal, their hashes must be equal. Violating
this property is a logic error.

It is also a logic error for a key to be modified in such a way that the
keyâs hash, as determined by the [ ` Hash ` ](../hash/trait.Hash.html "trait
std::hash::Hash") trait, or its equality, as determined by the [ ` Eq `
](../cmp/trait.Eq.html "trait std::cmp::Eq") trait, changes while it is in the
map. This is normally only possible through [ ` Cell `
](../cell/struct.Cell.html "struct std::cell::Cell") , [ ` RefCell `
](../cell/struct.RefCell.html "struct std::cell::RefCell") , global state,
I/O, or unsafe code.

The behavior resulting from either logic error is not specified, but will be
encapsulated to the ` HashMap ` that observed the logic error and not result
in undefined behavior. This could include panics, incorrect results, aborts,
memory leaks, and non-termination.

The hash table implementation is a Rust port of Googleâs [ SwissTable
](https://abseil.io/blog/20180927-swisstables) . The original C++ version of
SwissTable can be found [ here ](https://github.com/abseil/abseil-
cpp/blob/master/absl/container/internal/raw_hash_set.h) , and this [ CppCon
talk ](https://www.youtube.com/watch?v=ncHmEUmJZf4) gives an overview of how
the algorithm works.

##  Â§  Examples

    use std::collections::HashMap;

    // Type inference lets us omit an explicit type signature (which
    // would be `HashMap<String, String>` in this example).
    let mut book_reviews = HashMap::new();

    // Review some books.
    book_reviews.insert(
        "Adventures of Huckleberry Finn".to_string(),
        "My favorite book.".to_string(),
    );
    book_reviews.insert(
        "Grimms' Fairy Tales".to_string(),
        "Masterpiece.".to_string(),
    );
    book_reviews.insert(
        "Pride and Prejudice".to_string(),
        "Very enjoyable.".to_string(),
    );
    book_reviews.insert(
        "The Adventures of Sherlock Holmes".to_string(),
        "Eye lyked it alot.".to_string(),
    );

    // Check for a specific one.
    // When collections store owned values (String), they can still be
    // queried using references (&str).
    if !book_reviews.contains_key("Les MisÃ©rables") {
        println!("We've got {} reviews, but Les MisÃ©rables ain't one.",
                 book_reviews.len());
    }

    // oops, this review has a lot of spelling mistakes, let's delete it.
    book_reviews.remove("The Adventures of Sherlock Holmes");

    // Look up the values associated with some keys.
    let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
    for &book in &to_find {
        match book_reviews.get(book) {
            Some(review) => println!("{book}: {review}"),
            None => println!("{book} is unreviewed.")
        }
    }

    // Look up the value for a key (will panic if the key is not found).
    println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);

    // Iterate over everything.
    for (book, review) in &book_reviews {
        println!("{book}: \"{review}\"");
    }

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++//+Type+inference+lets+us+omit+an+explicit+type+signature+\(which%0A++++//+would+be+%60HashMap%3CString,+String%3E%60+in+this+example\).%0A++++let+mut+book_reviews+=+HashMap::new\(\);%0A++++%0A++++//+Review+some+books.%0A++++book_reviews.insert\(%0A++++++++%22Adventures+of+Huckleberry+Finn%22.to_string\(\),%0A++++++++%22My+favorite+book.%22.to_string\(\),%0A++++\);%0A++++book_reviews.insert\(%0A++++++++%22Grimms'+Fairy+Tales%22.to_string\(\),%0A++++++++%22Masterpiece.%22.to_string\(\),%0A++++\);%0A++++book_reviews.insert\(%0A++++++++%22Pride+and+Prejudice%22.to_string\(\),%0A++++++++%22Very+enjoyable.%22.to_string\(\),%0A++++\);%0A++++book_reviews.insert\(%0A++++++++%22The+Adventures+of+Sherlock+Holmes%22.to_string\(\),%0A++++++++%22Eye+lyked+it+alot.%22.to_string\(\),%0A++++\);%0A++++%0A++++//+Check+for+a+specific+one.%0A++++//+When+collections+store+owned+values+\(String\),+they+can+still+be%0A++++//+queried+using+references+\(%26str\).%0A++++if+!book_reviews.contains_key\(%22Les+Mis%C3%A9rables%22\)+%7B%0A++++++++println!\(%22We've+got+%7B%7D+reviews,+but+Les+Mis%C3%A9rables+ain't+one.%22,%0A+++++++++++++++++book_reviews.len\(\)\);%0A++++%7D%0A++++%0A++++//+oops,+this+review+has+a+lot+of+spelling+mistakes,+let's+delete+it.%0A++++book_reviews.remove\(%22The+Adventures+of+Sherlock+Holmes%22\);%0A++++%0A++++//+Look+up+the+values+associated+with+some+keys.%0A++++let+to_find+=+%5B%22Pride+and+Prejudice%22,+%22Alice's+Adventure+in+Wonderland%22%5D;%0A++++for+%26book+in+%26to_find+%7B%0A++++++++match+book_reviews.get\(book\)+%7B%0A++++++++++++Some\(review\)+=%3E+println!\(%22%7Bbook%7D:+%7Breview%7D%22\),%0A++++++++++++None+=%3E+println!\(%22%7Bbook%7D+is+unreviewed.%22\)%0A++++++++%7D%0A++++%7D%0A++++%0A++++//+Look+up+the+value+for+a+key+\(will+panic+if+the+key+is+not+found\).%0A++++println!\(%22Review+for+Jane:+%7B%7D%22,+book_reviews%5B%22Pride+and+Prejudice%22%5D\);%0A++++%0A++++//+Iterate+over+everything.%0A++++for+\(book,+review\)+in+%26book_reviews+%7B%0A++++++++println!\(%22%7Bbook%7D:+%5C%22%7Breview%7D%5C%22%22\);%0A++++%7D%0A%7D&edition=2021)

A ` HashMap ` with a known list of items can be initialized from an array:

    use std::collections::HashMap;

    let solar_distance = HashMap::from([
        ("Mercury", 0.4),
        ("Venus", 0.7),
        ("Earth", 1.0),
        ("Mars", 1.5),
    ]);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+solar_distance+=+HashMap::from\(%5B%0A++++++++\(%22Mercury%22,+0.4\),%0A++++++++\(%22Venus%22,+0.7\),%0A++++++++\(%22Earth%22,+1.0\),%0A++++++++\(%22Mars%22,+1.5\),%0A++++%5D\);%0A%7D&edition=2021)

` HashMap ` implements an  ` Entry ` API  , which allows for complex methods
of getting, setting, updating and removing keys and their values:

    use std::collections::HashMap;

    // type inference lets us omit an explicit type signature (which
    // would be `HashMap<&str, u8>` in this example).
    let mut player_stats = HashMap::new();

    fn random_stat_buff() -> u8 {
        // could actually return some random value here - let's just return
        // some fixed value for now
        42
    }

    // insert a key only if it doesn't already exist
    player_stats.entry("health").or_insert(100);

    // insert a key using a function that provides a new value only if it
    // doesn't already exist
    player_stats.entry("defence").or_insert_with(random_stat_buff);

    // update a key, guarding against the key possibly not being set
    let stat = player_stats.entry("attack").or_insert(100);
    *stat += random_stat_buff();

    // modify an entry before an insert with in-place mutation
    player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++//+type+inference+lets+us+omit+an+explicit+type+signature+\(which%0A++++//+would+be+%60HashMap%3C%26str,+u8%3E%60+in+this+example\).%0A++++let+mut+player_stats+=+HashMap::new\(\);%0A++++%0A++++fn+random_stat_buff\(\)+-%3E+u8+%7B%0A++++++++//+could+actually+return+some+random+value+here+-+let's+just+return%0A++++++++//+some+fixed+value+for+now%0A++++++++42%0A++++%7D%0A++++%0A++++//+insert+a+key+only+if+it+doesn't+already+exist%0A++++player_stats.entry\(%22health%22\).or_insert\(100\);%0A++++%0A++++//+insert+a+key+using+a+function+that+provides+a+new+value+only+if+it%0A++++//+doesn't+already+exist%0A++++player_stats.entry\(%22defence%22\).or_insert_with\(random_stat_buff\);%0A++++%0A++++//+update+a+key,+guarding+against+the+key+possibly+not+being+set%0A++++let+stat+=+player_stats.entry\(%22attack%22\).or_insert\(100\);%0A++++*stat+%2B=+random_stat_buff\(\);%0A++++%0A++++//+modify+an+entry+before+an+insert+with+in-
place+mutation%0A++++player_stats.entry\(%22mana%22\).and_modify\(%7Cmana%7C+*mana+%2B=+200\).or_insert\(100\);%0A%7D&edition=2021)

The easiest way to use ` HashMap ` with a custom key type is to derive [ ` Eq
` ](../cmp/trait.Eq.html "trait std::cmp::Eq") and [ ` Hash `
](../hash/trait.Hash.html "trait std::hash::Hash") . We must also derive [ `
PartialEq ` ](../cmp/trait.PartialEq.html "trait std::cmp::PartialEq") .

    use std::collections::HashMap;

    #[derive(Hash, Eq, PartialEq, Debug)]
    struct Viking {
        name: String,
        country: String,
    }

    impl Viking {
        /// Creates a new Viking.
        fn new(name: &str, country: &str) -> Viking {
            Viking { name: name.to_string(), country: country.to_string() }
        }
    }

    // Use a HashMap to store the vikings' health points.
    let vikings = HashMap::from([
        (Viking::new("Einar", "Norway"), 25),
        (Viking::new("Olaf", "Denmark"), 24),
        (Viking::new("Harald", "Iceland"), 12),
    ]);

    // Use derived implementation to print the status of the vikings.
    for (viking, health) in &vikings {
        println!("{viking:?} has {health} hp");
    }

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++%23%5Bderive\(Hash,+Eq,+PartialEq,+Debug\)%5D%0A++++struct+Viking+%7B%0A++++++++name:+String,%0A++++++++country:+String,%0A++++%7D%0A++++%0A++++impl+Viking+%7B%0A++++++++///+Creates+a+new+Viking.%0A++++++++fn+new\(name:+%26str,+country:+%26str\)+-%3E+Viking+%7B%0A++++++++++++Viking+%7B+name:+name.to_string\(\),+country:+country.to_string\(\)+%7D%0A++++++++%7D%0A++++%7D%0A++++%0A++++//+Use+a+HashMap+to+store+the+vikings'+health+points.%0A++++let+vikings+=+HashMap::from\(%5B%0A++++++++\(Viking::new\(%22Einar%22,+%22Norway%22\),+25\),%0A++++++++\(Viking::new\(%22Olaf%22,+%22Denmark%22\),+24\),%0A++++++++\(Viking::new\(%22Harald%22,+%22Iceland%22\),+12\),%0A++++%5D\);%0A++++%0A++++//+Use+derived+implementation+to+print+the+status+of+the+vikings.%0A++++for+\(viking,+health\)+in+%26vikings+%7B%0A++++++++println!\(%22%7Bviking:?%7D+has+%7Bhealth%7D+hp%22\);%0A++++%7D%0A%7D&edition=2021)

##  Implementations  Â§

[ source ](../../src/std/collections/hash/map.rs.html#217-254) Â§

###  impl<K, V> [ HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, [ RandomState
](hash_map/struct.RandomState.html "struct
std::collections::hash_map::RandomState") >

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#232-234)

####  pub fn  new  () -> [ HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, [ RandomState
](hash_map/struct.RandomState.html "struct
std::collections::hash_map::RandomState") >

Creates an empty ` HashMap ` .

The hash map is initially created with a capacity of 0, so it will not
allocate until it is first inserted into.

#####  Â§  Examples

    use std::collections::HashMap;
    let mut map: HashMap<&str, i32> = HashMap::new();

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++let+mut+map:+HashMap%3C%26str,+i32%3E+=+HashMap::new\(\);%0A%7D&edition=2021)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#251-253)

####  pub fn  with_capacity  (capacity: [ usize ](../primitive.usize.html) )
-> [ HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, [ RandomState
](hash_map/struct.RandomState.html "struct
std::collections::hash_map::RandomState") >

Creates an empty ` HashMap ` with at least the specified capacity.

The hash map will be able to hold at least ` capacity ` elements without
reallocating. This method is allowed to allocate for more elements than `
capacity ` . If ` capacity ` is 0, the hash map will not allocate.

#####  Â§  Examples

    use std::collections::HashMap;
    let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++let+mut+map:+HashMap%3C%26str,+i32%3E+=+HashMap::with_capacity\(10\);%0A%7D&edition=2021)

[ source ](../../src/std/collections/hash/map.rs.html#256-731) Â§

###  impl<K, V, S> [ HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>

1.7.0 (const: [ unstable ](https://github.com/rust-lang/rust/issues/102575
"Tracking issue for const_collections_with_hasher") )  Â· [ source
](../../src/std/collections/hash/map.rs.html#283-285)

####  pub fn  with_hasher  (hash_builder: S) -> [ HashMap
](hash_map/struct.HashMap.html "struct std::collections::hash_map::HashMap")
<K, V, S>

Creates an empty ` HashMap ` which will use the given hash builder to hash
keys.

The created map has the default initial capacity.

Warning: ` hash_builder ` is normally randomly generated, and is designed to
allow HashMaps to be resistant to attacks that cause many collisions and very
poor performance. Setting it manually using this function can expose a DoS
attack vector.

The ` hash_builder ` passed should implement the [ ` BuildHasher `
](../hash/trait.BuildHasher.html "trait std::hash::BuildHasher") trait for the
HashMap to be useful, see its documentation for details.

#####  Â§  Examples

    use std::collections::HashMap;
    use std::hash::RandomState;

    let s = RandomState::new();
    let mut map = HashMap::with_hasher(s);
    map.insert(1, 2);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++use+std::hash::RandomState;%0A++++%0A++++let+s+=+RandomState::new\(\);%0A++++let+mut+map+=+HashMap::with_hasher\(s\);%0A++++map.insert\(1,+2\);%0A%7D&edition=2021)

1.7.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#314-316)

####  pub fn  with_capacity_and_hasher  (capacity: [ usize
](../primitive.usize.html) , hasher: S) -> [ HashMap
](hash_map/struct.HashMap.html "struct std::collections::hash_map::HashMap")
<K, V, S>

Creates an empty ` HashMap ` with at least the specified capacity, using `
hasher ` to hash the keys.

The hash map will be able to hold at least ` capacity ` elements without
reallocating. This method is allowed to allocate for more elements than `
capacity ` . If ` capacity ` is 0, the hash map will not allocate.

Warning: ` hasher ` is normally randomly generated, and is designed to allow
HashMaps to be resistant to attacks that cause many collisions and very poor
performance. Setting it manually using this function can expose a DoS attack
vector.

The ` hasher ` passed should implement the [ ` BuildHasher `
](../hash/trait.BuildHasher.html "trait std::hash::BuildHasher") trait for the
HashMap to be useful, see its documentation for details.

#####  Â§  Examples

    use std::collections::HashMap;
    use std::hash::RandomState;

    let s = RandomState::new();
    let mut map = HashMap::with_capacity_and_hasher(10, s);
    map.insert(1, 2);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++use+std::hash::RandomState;%0A++++%0A++++let+s+=+RandomState::new\(\);%0A++++let+mut+map+=+HashMap::with_capacity_and_hasher\(10,+s\);%0A++++map.insert\(1,+2\);%0A%7D&edition=2021)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#332-334)

####  pub fn  capacity  (&self) -> [ usize ](../primitive.usize.html)

Returns the number of elements the map can hold without reallocating.

This number is a lower bound; the ` HashMap<K, V> ` might be able to hold
more, but is guaranteed to be able to hold at least this many.

#####  Â§  Examples

    use std::collections::HashMap;
    let map: HashMap<i32, i32> = HashMap::with_capacity(100);
    assert!(map.capacity() >= 100);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++let+map:+HashMap%3Ci32,+i32%3E+=+HashMap::with_capacity\(100\);%0A++++assert!\(map.capacity\(\)+%3E=+100\);%0A%7D&edition=2021)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#361-363)

####  pub fn  keys  (&self) -> [ Keys ](hash_map/struct.Keys.html "struct
std::collections::hash_map::Keys") <'_, K, V> â

An iterator visiting all keys in arbitrary order. The iterator element type is
` &'a K ` .

#####  Â§  Examples

    use std::collections::HashMap;

    let map = HashMap::from([
        ("a", 1),
        ("b", 2),
        ("c", 3),
    ]);

    for key in map.keys() {
        println!("{key}");
    }

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+map+=+HashMap::from\(%5B%0A++++++++\(%22a%22,+1\),%0A++++++++\(%22b%22,+2\),%0A++++++++\(%22c%22,+3\),%0A++++%5D\);%0A++++%0A++++for+key+in+map.keys\(\)+%7B%0A++++++++println!\(%22%7Bkey%7D%22\);%0A++++%7D%0A%7D&edition=2021)

#####  Â§  Performance

In the current implementation, iterating over keys takes O(capacity) time
instead of O(len) because it internally visits empty buckets too.

1.54.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#394-396)

####  pub fn  into_keys  (self) -> [ IntoKeys ](hash_map/struct.IntoKeys.html
"struct std::collections::hash_map::IntoKeys") <K, V> â

Creates a consuming iterator visiting all the keys in arbitrary order. The map
cannot be used after calling this. The iterator element type is ` K ` .

#####  Â§  Examples

    use std::collections::HashMap;

    let map = HashMap::from([
        ("a", 1),
        ("b", 2),
        ("c", 3),
    ]);

    let mut vec: Vec<&str> = map.into_keys().collect();
    // The `IntoKeys` iterator produces keys in arbitrary order, so the
    // keys must be sorted to test them against a sorted array.
    vec.sort_unstable();
    assert_eq!(vec, ["a", "b", "c"]);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+map+=+HashMap::from\(%5B%0A++++++++\(%22a%22,+1\),%0A++++++++\(%22b%22,+2\),%0A++++++++\(%22c%22,+3\),%0A++++%5D\);%0A++++%0A++++let+mut+vec:+Vec%3C%26str%3E+=+map.into_keys\(\).collect\(\);%0A++++//+The+%60IntoKeys%60+iterator+produces+keys+in+arbitrary+order,+so+the%0A++++//+keys+must+be+sorted+to+test+them+against+a+sorted+array.%0A++++vec.sort_unstable\(\);%0A++++assert_eq!\(vec,+%5B%22a%22,+%22b%22,+%22c%22%5D\);%0A%7D&edition=2021)

#####  Â§  Performance

In the current implementation, iterating over keys takes O(capacity) time
instead of O(len) because it internally visits empty buckets too.

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#423-425)

####  pub fn  values  (&self) -> [ Values ](hash_map/struct.Values.html
"struct std::collections::hash_map::Values") <'_, K, V> â

An iterator visiting all values in arbitrary order. The iterator element type
is ` &'a V ` .

#####  Â§  Examples

    use std::collections::HashMap;

    let map = HashMap::from([
        ("a", 1),
        ("b", 2),
        ("c", 3),
    ]);

    for val in map.values() {
        println!("{val}");
    }

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+map+=+HashMap::from\(%5B%0A++++++++\(%22a%22,+1\),%0A++++++++\(%22b%22,+2\),%0A++++++++\(%22c%22,+3\),%0A++++%5D\);%0A++++%0A++++for+val+in+map.values\(\)+%7B%0A++++++++println!\(%22%7Bval%7D%22\);%0A++++%7D%0A%7D&edition=2021)

#####  Â§  Performance

In the current implementation, iterating over values takes O(capacity) time
instead of O(len) because it internally visits empty buckets too.

1.10.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#456-458)

####  pub fn  values_mut  (&mut self) -> [ ValuesMut
](hash_map/struct.ValuesMut.html "struct
std::collections::hash_map::ValuesMut") <'_, K, V> â

An iterator visiting all values mutably in arbitrary order. The iterator
element type is ` &'a mut V ` .

#####  Â§  Examples

    use std::collections::HashMap;

    let mut map = HashMap::from([
        ("a", 1),
        ("b", 2),
        ("c", 3),
    ]);

    for val in map.values_mut() {
        *val = *val + 10;
    }

    for val in map.values() {
        println!("{val}");
    }

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+map+=+HashMap::from\(%5B%0A++++++++\(%22a%22,+1\),%0A++++++++\(%22b%22,+2\),%0A++++++++\(%22c%22,+3\),%0A++++%5D\);%0A++++%0A++++for+val+in+map.values_mut\(\)+%7B%0A++++++++*val+=+*val+%2B+10;%0A++++%7D%0A++++%0A++++for+val+in+map.values\(\)+%7B%0A++++++++println!\(%22%7Bval%7D%22\);%0A++++%7D%0A%7D&edition=2021)

#####  Â§  Performance

In the current implementation, iterating over values takes O(capacity) time
instead of O(len) because it internally visits empty buckets too.

1.54.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#489-491)

####  pub fn  into_values  (self) -> [ IntoValues
](hash_map/struct.IntoValues.html "struct
std::collections::hash_map::IntoValues") <K, V> â

Creates a consuming iterator visiting all the values in arbitrary order. The
map cannot be used after calling this. The iterator element type is ` V ` .

#####  Â§  Examples

    use std::collections::HashMap;

    let map = HashMap::from([
        ("a", 1),
        ("b", 2),
        ("c", 3),
    ]);

    let mut vec: Vec<i32> = map.into_values().collect();
    // The `IntoValues` iterator produces values in arbitrary order, so
    // the values must be sorted to test them against a sorted array.
    vec.sort_unstable();
    assert_eq!(vec, [1, 2, 3]);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+map+=+HashMap::from\(%5B%0A++++++++\(%22a%22,+1\),%0A++++++++\(%22b%22,+2\),%0A++++++++\(%22c%22,+3\),%0A++++%5D\);%0A++++%0A++++let+mut+vec:+Vec%3Ci32%3E+=+map.into_values\(\).collect\(\);%0A++++//+The+%60IntoValues%60+iterator+produces+values+in+arbitrary+order,+so%0A++++//+the+values+must+be+sorted+to+test+them+against+a+sorted+array.%0A++++vec.sort_unstable\(\);%0A++++assert_eq!\(vec,+%5B1,+2,+3%5D\);%0A%7D&edition=2021)

#####  Â§  Performance

In the current implementation, iterating over values takes O(capacity) time
instead of O(len) because it internally visits empty buckets too.

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#518-520)

####  pub fn  iter  (&self) -> [ Iter ](hash_map/struct.Iter.html "struct
std::collections::hash_map::Iter") <'_, K, V> â

An iterator visiting all key-value pairs in arbitrary order. The iterator
element type is ` (&'a K, &'a V) ` .

#####  Â§  Examples

    use std::collections::HashMap;

    let map = HashMap::from([
        ("a", 1),
        ("b", 2),
        ("c", 3),
    ]);

    for (key, val) in map.iter() {
        println!("key: {key} val: {val}");
    }

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+map+=+HashMap::from\(%5B%0A++++++++\(%22a%22,+1\),%0A++++++++\(%22b%22,+2\),%0A++++++++\(%22c%22,+3\),%0A++++%5D\);%0A++++%0A++++for+\(key,+val\)+in+map.iter\(\)+%7B%0A++++++++println!\(%22key:+%7Bkey%7D+val:+%7Bval%7D%22\);%0A++++%7D%0A%7D&edition=2021)

#####  Â§  Performance

In the current implementation, iterating over map takes O(capacity) time
instead of O(len) because it internally visits empty buckets too.

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#553-555)

####  pub fn  iter_mut  (&mut self) -> [ IterMut
](hash_map/struct.IterMut.html "struct std::collections::hash_map::IterMut")
<'_, K, V> â

An iterator visiting all key-value pairs in arbitrary order, with mutable
references to the values. The iterator element type is ` (&'a K, &'a mut V) `
.

#####  Â§  Examples

    use std::collections::HashMap;

    let mut map = HashMap::from([
        ("a", 1),
        ("b", 2),
        ("c", 3),
    ]);

    // Update all values
    for (_, val) in map.iter_mut() {
        *val *= 2;
    }

    for (key, val) in &map {
        println!("key: {key} val: {val}");
    }

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+map+=+HashMap::from\(%5B%0A++++++++\(%22a%22,+1\),%0A++++++++\(%22b%22,+2\),%0A++++++++\(%22c%22,+3\),%0A++++%5D\);%0A++++%0A++++//+Update+all+values%0A++++for+\(_,+val\)+in+map.iter_mut\(\)+%7B%0A++++++++*val+*=+2;%0A++++%7D%0A++++%0A++++for+\(key,+val\)+in+%26map+%7B%0A++++++++println!\(%22key:+%7Bkey%7D+val:+%7Bval%7D%22\);%0A++++%7D%0A%7D&edition=2021)

#####  Â§  Performance

In the current implementation, iterating over map takes O(capacity) time
instead of O(len) because it internally visits empty buckets too.

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#570-572)

####  pub fn  len  (&self) -> [ usize ](../primitive.usize.html)

Returns the number of elements in the map.

#####  Â§  Examples

    use std::collections::HashMap;

    let mut a = HashMap::new();
    assert_eq!(a.len(), 0);
    a.insert(1, "a");
    assert_eq!(a.len(), 1);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+a+=+HashMap::new\(\);%0A++++assert_eq!\(a.len\(\),+0\);%0A++++a.insert\(1,+%22a%22\);%0A++++assert_eq!\(a.len\(\),+1\);%0A%7D&edition=2021)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#588-590)

####  pub fn  is_empty  (&self) -> [ bool ](../primitive.bool.html)

Returns ` true ` if the map contains no elements.

#####  Â§  Examples

    use std::collections::HashMap;

    let mut a = HashMap::new();
    assert!(a.is_empty());
    a.insert(1, "a");
    assert!(!a.is_empty());

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+a+=+HashMap::new\(\);%0A++++assert!\(a.is_empty\(\)\);%0A++++a.insert\(1,+%22a%22\);%0A++++assert!\(!a.is_empty\(\)\);%0A%7D&edition=2021)

1.6.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#618-620)

####  pub fn  drain  (&mut self) -> [ Drain ](hash_map/struct.Drain.html
"struct std::collections::hash_map::Drain") <'_, K, V> â

Clears the map, returning all key-value pairs as an iterator. Keeps the
allocated memory for reuse.

If the returned iterator is dropped before being fully consumed, it drops the
remaining key-value pairs. The returned iterator keeps a mutable borrow on the
map to optimize its implementation.

#####  Â§  Examples

    use std::collections::HashMap;

    let mut a = HashMap::new();
    a.insert(1, "a");
    a.insert(2, "b");

    for (k, v) in a.drain().take(1) {
        assert!(k == 1 || k == 2);
        assert!(v == "a" || v == "b");
    }

    assert!(a.is_empty());

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+a+=+HashMap::new\(\);%0A++++a.insert\(1,+%22a%22\);%0A++++a.insert\(2,+%22b%22\);%0A++++%0A++++for+\(k,+v\)+in+a.drain\(\).take\(1\)+%7B%0A++++++++assert!\(k+==+1+%7C%7C+k+==+2\);%0A++++++++assert!\(v+==+%22a%22+%7C%7C+v+==+%22b%22\);%0A++++%7D%0A++++%0A++++assert!\(a.is_empty\(\)\);%0A%7D&edition=2021)

[ source ](../../src/std/collections/hash/map.rs.html#659-664)

####  pub fn  extract_if  <F>(&mut self, pred: F) -> [ ExtractIf
](hash_map/struct.ExtractIf.html "struct
std::collections::hash_map::ExtractIf") <'_, K, V, F> â

where F: [ FnMut ](../ops/trait.FnMut.html "trait std::ops::FnMut") ( [ &K
](../primitive.reference.html) , [ &mut V ](../primitive.reference.html) ) ->
[ bool ](../primitive.bool.html) ,

ð¬  This is a nightly-only experimental API. ( ` hash_extract_if ` [ #59618
](https://github.com/rust-lang/rust/issues/59618) )

Creates an iterator which uses a closure to determine if an element should be
removed.

If the closure returns true, the element is removed from the map and yielded.
If the closure returns false, or panics, the element remains in the map and
will not be yielded.

Note that ` extract_if ` lets you mutate every value in the filter closure,
regardless of whether you choose to keep or remove it.

If the returned ` ExtractIf ` is not exhausted, e.g. because it is dropped
without iterating or the iteration short-circuits, then the remaining elements
will be retained. Use [ ` retain `
](hash_map/struct.HashMap.html#method.retain "method
std::collections::hash_map::HashMap::retain") with a negated predicate if you
do not need the returned iterator.

#####  Â§  Examples

Splitting a map into even and odd keys, reusing the original map:

    #![feature(hash_extract_if)]
    use std::collections::HashMap;

    let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
    let extracted: HashMap<i32, i32> = map.extract_if(|k, _v| k % 2 == 0).collect();

    let mut evens = extracted.keys().copied().collect::<Vec<_>>();
    let mut odds = map.keys().copied().collect::<Vec<_>>();
    evens.sort();
    odds.sort();

    assert_eq!(evens, vec![0, 2, 4, 6]);
    assert_eq!(odds, vec![1, 3, 5, 7]);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0A%23!%5Bfeature\(hash_extract_if\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+map:+HashMap%3Ci32,+i32%3E+=+\(0..8\).map\(%7Cx%7C+\(x,+x\)\).collect\(\);%0A++++let+extracted:+HashMap%3Ci32,+i32%3E+=+map.extract_if\(%7Ck,+_v%7C+k+%25+2+==+0\).collect\(\);%0A++++%0A++++let+mut+evens+=+extracted.keys\(\).copied\(\).collect::%3CVec%3C_%3E%3E\(\);%0A++++let+mut+odds+=+map.keys\(\).copied\(\).collect::%3CVec%3C_%3E%3E\(\);%0A++++evens.sort\(\);%0A++++odds.sort\(\);%0A++++%0A++++assert_eq!\(evens,+vec!%5B0,+2,+4,+6%5D\);%0A++++assert_eq!\(odds,+vec!%5B1,+3,+5,+7%5D\);%0A%7D&version=nightly&edition=2021)

1.18.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#688-693)

####  pub fn  retain  <F>(&mut self, f: F)

where F: [ FnMut ](../ops/trait.FnMut.html "trait std::ops::FnMut") ( [ &K
](../primitive.reference.html) , [ &mut V ](../primitive.reference.html) ) ->
[ bool ](../primitive.bool.html) ,

Retains only the elements specified by the predicate.

In other words, remove all pairs ` (k, v) ` for which ` f(&k, &mut v) `
returns ` false ` . The elements are visited in unsorted (and unspecified)
order.

#####  Â§  Examples

    use std::collections::HashMap;

    let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
    map.retain(|&k, _| k % 2 == 0);
    assert_eq!(map.len(), 4);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+map:+HashMap%3Ci32,+i32%3E+=+\(0..8\).map\(%7Cx%7C+\(x,+x*10\)\).collect\(\);%0A++++map.retain\(%7C%26k,+_%7C+k+%25+2+==+0\);%0A++++assert_eq!\(map.len\(\),+4\);%0A%7D&edition=2021)

#####  Â§  Performance

In the current implementation, this operation takes O(capacity) time instead
of O(len) because it internally visits empty buckets too.

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#710-712)

####  pub fn  clear  (&mut self)

Clears the map, removing all key-value pairs. Keeps the allocated memory for
reuse.

#####  Â§  Examples

    use std::collections::HashMap;

    let mut a = HashMap::new();
    a.insert(1, "a");
    a.clear();
    assert!(a.is_empty());

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+a+=+HashMap::new\(\);%0A++++a.insert\(1,+%22a%22\);%0A++++a.clear\(\);%0A++++assert!\(a.is_empty\(\)\);%0A%7D&edition=2021)

1.9.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#728-730)

####  pub fn  hasher  (&self) -> [ &S ](../primitive.reference.html)

Returns a reference to the mapâs [ ` BuildHasher `
](../hash/trait.BuildHasher.html "trait std::hash::BuildHasher") .

#####  Â§  Examples

    use std::collections::HashMap;
    use std::hash::RandomState;

    let hasher = RandomState::new();
    let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
    let hasher: &RandomState = map.hasher();

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++use+std::hash::RandomState;%0A++++%0A++++let+hasher+=+RandomState::new\(\);%0A++++let+map:+HashMap%3Ci32,+i32%3E+=+HashMap::with_hasher\(hasher\);%0A++++let+hasher:+%26RandomState+=+map.hasher\(\);%0A%7D&edition=2021)

[ source ](../../src/std/collections/hash/map.rs.html#733-1196) Â§

###  impl<K, V, S> [ HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>

where K: [ Eq ](../cmp/trait.Eq.html "trait std::cmp::Eq") \+ [ Hash
](../hash/trait.Hash.html "trait std::hash::Hash") , S: [ BuildHasher
](../hash/trait.BuildHasher.html "trait std::hash::BuildHasher") ,

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#757-759)

####  pub fn  reserve  (&mut self, additional: [ usize
](../primitive.usize.html) )

Reserves capacity for at least ` additional ` more elements to be inserted in
the ` HashMap ` . The collection may reserve more space to speculatively avoid
frequent reallocations. After calling ` reserve ` , capacity will be greater
than or equal to ` self.len() + additional ` . Does nothing if capacity is
already sufficient.

#####  Â§  Panics

Panics if the new allocation size overflows [ ` usize `
](../primitive.usize.html "primitive usize") .

#####  Â§  Examples

    use std::collections::HashMap;
    let mut map: HashMap<&str, i32> = HashMap::new();
    map.reserve(10);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++let+mut+map:+HashMap%3C%26str,+i32%3E+=+HashMap::new\(\);%0A++++map.reserve\(10\);%0A%7D&edition=2021)

1.57.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#783-785)

####  pub fn  try_reserve  (&mut self, additional: [ usize
](../primitive.usize.html) ) -> [ Result ](../result/enum.Result.html "enum
std::result::Result") < [ () ](../primitive.unit.html) , [ TryReserveError
](struct.TryReserveError.html "struct std::collections::TryReserveError") >

Tries to reserve capacity for at least ` additional ` more elements to be
inserted in the ` HashMap ` . The collection may reserve more space to
speculatively avoid frequent reallocations. After calling ` try_reserve ` ,
capacity will be greater than or equal to ` self.len() + additional ` if it
returns ` Ok(()) ` . Does nothing if capacity is already sufficient.

#####  Â§  Errors

If the capacity overflows, or the allocator reports a failure, then an error
is returned.

#####  Â§  Examples

    use std::collections::HashMap;

    let mut map: HashMap<&str, isize> = HashMap::new();
    map.try_reserve(10).expect("why is the test harness OOMing on a handful of bytes?");

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+map:+HashMap%3C%26str,+isize%3E+=+HashMap::new\(\);%0A++++map.try_reserve\(10\).expect\(%22why+is+the+test+harness+OOMing+on+a+handful+of+bytes?%22\);%0A%7D&edition=2021)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#805-807)

####  pub fn  shrink_to_fit  (&mut self)

Shrinks the capacity of the map as much as possible. It will drop down as much
as possible while maintaining the internal rules and possibly leaving some
space in accordance with the resize policy.

#####  Â§  Examples

    use std::collections::HashMap;

    let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
    map.insert(1, 2);
    map.insert(3, 4);
    assert!(map.capacity() >= 100);
    map.shrink_to_fit();
    assert!(map.capacity() >= 2);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+map:+HashMap%3Ci32,+i32%3E+=+HashMap::with_capacity\(100\);%0A++++map.insert\(1,+2\);%0A++++map.insert\(3,+4\);%0A++++assert!\(map.capacity\(\)+%3E=+100\);%0A++++map.shrink_to_fit\(\);%0A++++assert!\(map.capacity\(\)+%3E=+2\);%0A%7D&edition=2021)

1.56.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#831-833)

####  pub fn  shrink_to  (&mut self, min_capacity: [ usize
](../primitive.usize.html) )

Shrinks the capacity of the map with a lower limit. It will drop down no lower
than the supplied limit while maintaining the internal rules and possibly
leaving some space in accordance with the resize policy.

If the current capacity is less than the lower limit, this is a no-op.

#####  Â§  Examples

    use std::collections::HashMap;

    let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
    map.insert(1, 2);
    map.insert(3, 4);
    assert!(map.capacity() >= 100);
    map.shrink_to(10);
    assert!(map.capacity() >= 10);
    map.shrink_to(0);
    assert!(map.capacity() >= 2);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+map:+HashMap%3Ci32,+i32%3E+=+HashMap::with_capacity\(100\);%0A++++map.insert\(1,+2\);%0A++++map.insert\(3,+4\);%0A++++assert!\(map.capacity\(\)+%3E=+100\);%0A++++map.shrink_to\(10\);%0A++++assert!\(map.capacity\(\)+%3E=+10\);%0A++++map.shrink_to\(0\);%0A++++assert!\(map.capacity\(\)+%3E=+2\);%0A%7D&edition=2021)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#855-857)

####  pub fn  entry  (&mut self, key: K) -> [ Entry ](hash_map/enum.Entry.html
"enum std::collections::hash_map::Entry") <'_, K, V>

Gets the given keyâs corresponding entry in the map for in-place
manipulation.

#####  Â§  Examples

    use std::collections::HashMap;

    let mut letters = HashMap::new();

    for ch in "a short treatise on fungi".chars() {
        letters.entry(ch).and_modify(|counter| *counter += 1).or_insert(1);
    }

    assert_eq!(letters[&'s'], 2);
    assert_eq!(letters[&'t'], 3);
    assert_eq!(letters[&'u'], 1);
    assert_eq!(letters.get(&'y'), None);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+letters+=+HashMap::new\(\);%0A++++%0A++++for+ch+in+%22a+short+treatise+on+fungi%22.chars\(\)+%7B%0A++++++++letters.entry\(ch\).and_modify\(%7Ccounter%7C+*counter+%2B=+1\).or_insert\(1\);%0A++++%7D%0A++++%0A++++assert_eq!\(letters%5B%26's'%5D,+2\);%0A++++assert_eq!\(letters%5B%26't'%5D,+3\);%0A++++assert_eq!\(letters%5B%26'u'%5D,+1\);%0A++++assert_eq!\(letters.get\(%26'y'\),+None\);%0A%7D&edition=2021)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#877-883)

####  pub fn  get  <Q>(&self, k: [ &Q ](../primitive.reference.html) ) -> [
Option ](../option/enum.Option.html "enum std::option::Option") < [ &V
](../primitive.reference.html) >

where K: [ Borrow ](../borrow/trait.Borrow.html "trait std::borrow::Borrow")
<Q>, Q: [ Hash ](../hash/trait.Hash.html "trait std::hash::Hash") \+ [ Eq
](../cmp/trait.Eq.html "trait std::cmp::Eq") \+ ? [ Sized
](../marker/trait.Sized.html "trait std::marker::Sized") ,

Returns a reference to the value corresponding to the key.

The key may be any borrowed form of the mapâs key type, but [ ` Hash `
](../hash/trait.Hash.html "trait std::hash::Hash") and [ ` Eq `
](../cmp/trait.Eq.html "trait std::cmp::Eq") on the borrowed form _must_ match
those for the key type.

#####  Â§  Examples

    use std::collections::HashMap;

    let mut map = HashMap::new();
    map.insert(1, "a");
    assert_eq!(map.get(&1), Some(&"a"));
    assert_eq!(map.get(&2), None);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+map+=+HashMap::new\(\);%0A++++map.insert\(1,+%22a%22\);%0A++++assert_eq!\(map.get\(%261\),+Some\(%26%22a%22\)\);%0A++++assert_eq!\(map.get\(%262\),+None\);%0A%7D&edition=2021)

1.40.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#903-909)

####  pub fn  get_key_value  <Q>(&self, k: [ &Q ](../primitive.reference.html)
) -> [ Option ](../option/enum.Option.html "enum std::option::Option") <( [ &K
](../primitive.reference.html) , [ &V ](../primitive.reference.html) )>

where K: [ Borrow ](../borrow/trait.Borrow.html "trait std::borrow::Borrow")
<Q>, Q: [ Hash ](../hash/trait.Hash.html "trait std::hash::Hash") \+ [ Eq
](../cmp/trait.Eq.html "trait std::cmp::Eq") \+ ? [ Sized
](../marker/trait.Sized.html "trait std::marker::Sized") ,

Returns the key-value pair corresponding to the supplied key.

The supplied key may be any borrowed form of the mapâs key type, but [ `
Hash ` ](../hash/trait.Hash.html "trait std::hash::Hash") and [ ` Eq `
](../cmp/trait.Eq.html "trait std::cmp::Eq") on the borrowed form _must_ match
those for the key type.

#####  Â§  Examples

    use std::collections::HashMap;

    let mut map = HashMap::new();
    map.insert(1, "a");
    assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
    assert_eq!(map.get_key_value(&2), None);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+map+=+HashMap::new\(\);%0A++++map.insert\(1,+%22a%22\);%0A++++assert_eq!\(map.get_key_value\(%261\),+Some\(\(%261,+%26%22a%22\)\)\);%0A++++assert_eq!\(map.get_key_value\(%262\),+None\);%0A%7D&edition=2021)

[ source ](../../src/std/collections/hash/map.rs.html#957-963)

####  pub fn  get_many_mut  <Q, const N: [ usize ](../primitive.usize.html) >(
&mut self, ks: [ [ &Q ](../primitive.reference.html) ; [ N
](../primitive.array.html) ], ) -> [ Option ](../option/enum.Option.html "enum
std::option::Option") <[ [ &mut V ](../primitive.reference.html) ; [ N
](../primitive.array.html) ]>

where K: [ Borrow ](../borrow/trait.Borrow.html "trait std::borrow::Borrow")
<Q>, Q: [ Hash ](../hash/trait.Hash.html "trait std::hash::Hash") \+ [ Eq
](../cmp/trait.Eq.html "trait std::cmp::Eq") \+ ? [ Sized
](../marker/trait.Sized.html "trait std::marker::Sized") ,

ð¬  This is a nightly-only experimental API. ( ` map_many_mut ` [ #97601
](https://github.com/rust-lang/rust/issues/97601) )

Attempts to get mutable references to ` N ` values in the map at once.

Returns an array of length ` N ` with the results of each query. For
soundness, at most one mutable reference will be returned to any value. ` None
` will be returned if any of the keys are duplicates or missing.

#####  Â§  Examples

    #![feature(map_many_mut)]
    use std::collections::HashMap;

    let mut libraries = HashMap::new();
    libraries.insert("Bodleian Library".to_string(), 1602);
    libraries.insert("AthenÃ¦um".to_string(), 1807);
    libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
    libraries.insert("Library of Congress".to_string(), 1800);

    let got = libraries.get_many_mut([
        "AthenÃ¦um",
        "Library of Congress",
    ]);
    assert_eq!(
        got,
        Some([
            &mut 1807,
            &mut 1800,
        ]),
    );

    // Missing keys result in None
    let got = libraries.get_many_mut([
        "AthenÃ¦um",
        "New York Public Library",
    ]);
    assert_eq!(got, None);

    // Duplicate keys result in None
    let got = libraries.get_many_mut([
        "AthenÃ¦um",
        "AthenÃ¦um",
    ]);
    assert_eq!(got, None);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0A%23!%5Bfeature\(map_many_mut\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+libraries+=+HashMap::new\(\);%0A++++libraries.insert\(%22Bodleian+Library%22.to_string\(\),+1602\);%0A++++libraries.insert\(%22Athen%C3%A6um%22.to_string\(\),+1807\);%0A++++libraries.insert\(%22Herzogin-
Anna-Amalia-
Bibliothek%22.to_string\(\),+1691\);%0A++++libraries.insert\(%22Library+of+Congress%22.to_string\(\),+1800\);%0A++++%0A++++let+got+=+libraries.get_many_mut\(%5B%0A++++++++%22Athen%C3%A6um%22,%0A++++++++%22Library+of+Congress%22,%0A++++%5D\);%0A++++assert_eq!\(%0A++++++++got,%0A++++++++Some\(%5B%0A++++++++++++%26mut+1807,%0A++++++++++++%26mut+1800,%0A++++++++%5D\),%0A++++\);%0A++++%0A++++//+Missing+keys+result+in+None%0A++++let+got+=+libraries.get_many_mut\(%5B%0A++++++++%22Athen%C3%A6um%22,%0A++++++++%22New+York+Public+Library%22,%0A++++%5D\);%0A++++assert_eq!\(got,+None\);%0A++++%0A++++//+Duplicate+keys+result+in+None%0A++++let+got+=+libraries.get_many_mut\(%5B%0A++++++++%22Athen%C3%A6um%22,%0A++++++++%22Athen%C3%A6um%22,%0A++++%5D\);%0A++++assert_eq!\(got,+None\);%0A%7D&version=nightly&edition=2021)

[ source ](../../src/std/collections/hash/map.rs.html#1013-1022)

####  pub unsafe fn  get_many_unchecked_mut  <Q, const N: [ usize
](../primitive.usize.html) >( &mut self, ks: [ [ &Q
](../primitive.reference.html) ; [ N ](../primitive.array.html) ], ) -> [
Option ](../option/enum.Option.html "enum std::option::Option") <[ [ &mut V
](../primitive.reference.html) ; [ N ](../primitive.array.html) ]>

where K: [ Borrow ](../borrow/trait.Borrow.html "trait std::borrow::Borrow")
<Q>, Q: [ Hash ](../hash/trait.Hash.html "trait std::hash::Hash") \+ [ Eq
](../cmp/trait.Eq.html "trait std::cmp::Eq") \+ ? [ Sized
](../marker/trait.Sized.html "trait std::marker::Sized") ,

ð¬  This is a nightly-only experimental API. ( ` map_many_mut ` [ #97601
](https://github.com/rust-lang/rust/issues/97601) )

Attempts to get mutable references to ` N ` values in the map at once, without
validating that the values are unique.

Returns an array of length ` N ` with the results of each query. ` None ` will
be returned if any of the keys are missing.

For a safe alternative see [ ` get_many_mut `
](hash_map/struct.HashMap.html#method.get_many_mut "method
std::collections::hash_map::HashMap::get_many_mut") .

#####  Â§  Safety

Calling this method with overlapping keys is _[ undefined behavior
](https://doc.rust-lang.org/reference/behavior-considered-undefined.html) _
even if the resulting references are not used.

#####  Â§  Examples

    #![feature(map_many_mut)]
    use std::collections::HashMap;

    let mut libraries = HashMap::new();
    libraries.insert("Bodleian Library".to_string(), 1602);
    libraries.insert("AthenÃ¦um".to_string(), 1807);
    libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
    libraries.insert("Library of Congress".to_string(), 1800);

    let got = libraries.get_many_mut([
        "AthenÃ¦um",
        "Library of Congress",
    ]);
    assert_eq!(
        got,
        Some([
            &mut 1807,
            &mut 1800,
        ]),
    );

    // Missing keys result in None
    let got = libraries.get_many_mut([
        "AthenÃ¦um",
        "New York Public Library",
    ]);
    assert_eq!(got, None);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0A%23!%5Bfeature\(map_many_mut\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+libraries+=+HashMap::new\(\);%0A++++libraries.insert\(%22Bodleian+Library%22.to_string\(\),+1602\);%0A++++libraries.insert\(%22Athen%C3%A6um%22.to_string\(\),+1807\);%0A++++libraries.insert\(%22Herzogin-
Anna-Amalia-
Bibliothek%22.to_string\(\),+1691\);%0A++++libraries.insert\(%22Library+of+Congress%22.to_string\(\),+1800\);%0A++++%0A++++let+got+=+libraries.get_many_mut\(%5B%0A++++++++%22Athen%C3%A6um%22,%0A++++++++%22Library+of+Congress%22,%0A++++%5D\);%0A++++assert_eq!\(%0A++++++++got,%0A++++++++Some\(%5B%0A++++++++++++%26mut+1807,%0A++++++++++++%26mut+1800,%0A++++++++%5D\),%0A++++\);%0A++++%0A++++//+Missing+keys+result+in+None%0A++++let+got+=+libraries.get_many_mut\(%5B%0A++++++++%22Athen%C3%A6um%22,%0A++++++++%22New+York+Public+Library%22,%0A++++%5D\);%0A++++assert_eq!\(got,+None\);%0A%7D&version=nightly&edition=2021)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#1042-1048)

####  pub fn  contains_key  <Q>(&self, k: [ &Q ](../primitive.reference.html)
) -> [ bool ](../primitive.bool.html)

where K: [ Borrow ](../borrow/trait.Borrow.html "trait std::borrow::Borrow")
<Q>, Q: [ Hash ](../hash/trait.Hash.html "trait std::hash::Hash") \+ [ Eq
](../cmp/trait.Eq.html "trait std::cmp::Eq") \+ ? [ Sized
](../marker/trait.Sized.html "trait std::marker::Sized") ,

Returns ` true ` if the map contains a value for the specified key.

The key may be any borrowed form of the mapâs key type, but [ ` Hash `
](../hash/trait.Hash.html "trait std::hash::Hash") and [ ` Eq `
](../cmp/trait.Eq.html "trait std::cmp::Eq") on the borrowed form _must_ match
those for the key type.

#####  Â§  Examples

    use std::collections::HashMap;

    let mut map = HashMap::new();
    map.insert(1, "a");
    assert_eq!(map.contains_key(&1), true);
    assert_eq!(map.contains_key(&2), false);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+map+=+HashMap::new\(\);%0A++++map.insert\(1,+%22a%22\);%0A++++assert_eq!\(map.contains_key\(%261\),+true\);%0A++++assert_eq!\(map.contains_key\(%262\),+false\);%0A%7D&edition=2021)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#1070-1076)

####  pub fn  get_mut  <Q>(&mut self, k: [ &Q ](../primitive.reference.html) )
-> [ Option ](../option/enum.Option.html "enum std::option::Option") < [ &mut
V ](../primitive.reference.html) >

where K: [ Borrow ](../borrow/trait.Borrow.html "trait std::borrow::Borrow")
<Q>, Q: [ Hash ](../hash/trait.Hash.html "trait std::hash::Hash") \+ [ Eq
](../cmp/trait.Eq.html "trait std::cmp::Eq") \+ ? [ Sized
](../marker/trait.Sized.html "trait std::marker::Sized") ,

Returns a mutable reference to the value corresponding to the key.

The key may be any borrowed form of the mapâs key type, but [ ` Hash `
](../hash/trait.Hash.html "trait std::hash::Hash") and [ ` Eq `
](../cmp/trait.Eq.html "trait std::cmp::Eq") on the borrowed form _must_ match
those for the key type.

#####  Â§  Examples

    use std::collections::HashMap;

    let mut map = HashMap::new();
    map.insert(1, "a");
    if let Some(x) = map.get_mut(&1) {
        *x = "b";
    }
    assert_eq!(map[&1], "b");

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+map+=+HashMap::new\(\);%0A++++map.insert\(1,+%22a%22\);%0A++++if+let+Some\(x\)+=+map.get_mut\(%261\)+%7B%0A++++++++*x+=+%22b%22;%0A++++%7D%0A++++assert_eq!\(map%5B%261%5D,+%22b%22\);%0A%7D&edition=2021)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#1105-1107)

####  pub fn  insert  (&mut self, k: K, v: V) -> [ Option
](../option/enum.Option.html "enum std::option::Option") <V>

Inserts a key-value pair into the map.

If the map did not have this key present, [ ` None `
](../option/enum.Option.html#variant.None "variant std::option::Option::None")
is returned.

If the map did have this key present, the value is updated, and the old value
is returned. The key is not updated, though; this matters for types that can
be ` == ` without being identical. See the [ module-level documentation
](index.html#insert-and-complex-keys "mod std::collections") for more.

#####  Â§  Examples

    use std::collections::HashMap;

    let mut map = HashMap::new();
    assert_eq!(map.insert(37, "a"), None);
    assert_eq!(map.is_empty(), false);

    map.insert(37, "b");
    assert_eq!(map.insert(37, "c"), Some("b"));
    assert_eq!(map[&37], "c");

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+map+=+HashMap::new\(\);%0A++++assert_eq!\(map.insert\(37,+%22a%22\),+None\);%0A++++assert_eq!\(map.is_empty\(\),+false\);%0A++++%0A++++map.insert\(37,+%22b%22\);%0A++++assert_eq!\(map.insert\(37,+%22c%22\),+Some\(%22b%22\)\);%0A++++assert_eq!\(map%5B%2637%5D,+%22c%22\);%0A%7D&edition=2021)

[ source ](../../src/std/collections/hash/map.rs.html#1133-1138)

####  pub fn  try_insert  ( &mut self, key: K, value: V, ) -> [ Result
](../result/enum.Result.html "enum std::result::Result") < [ &mut V
](../primitive.reference.html) , [ OccupiedError
](hash_map/struct.OccupiedError.html "struct
std::collections::hash_map::OccupiedError") <'_, K, V>>

ð¬  This is a nightly-only experimental API. ( ` map_try_insert ` [ #82766
](https://github.com/rust-lang/rust/issues/82766) )

Tries to insert a key-value pair into the map, and returns a mutable reference
to the value in the entry.

If the map already had this key present, nothing is updated, and an error
containing the occupied entry and the value is returned.

#####  Â§  Examples

Basic usage:

    #![feature(map_try_insert)]

    use std::collections::HashMap;

    let mut map = HashMap::new();
    assert_eq!(map.try_insert(37, "a").unwrap(), &"a");

    let err = map.try_insert(37, "b").unwrap_err();
    assert_eq!(err.entry.key(), &37);
    assert_eq!(err.entry.get(), &"a");
    assert_eq!(err.value, "b");

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0A%23!%5Bfeature\(map_try_insert\)%5D%0A%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+map+=+HashMap::new\(\);%0A++++assert_eq!\(map.try_insert\(37,+%22a%22\).unwrap\(\),+%26%22a%22\);%0A++++%0A++++let+err+=+map.try_insert\(37,+%22b%22\).unwrap_err\(\);%0A++++assert_eq!\(err.entry.key\(\),+%2637\);%0A++++assert_eq!\(err.entry.get\(\),+%26%22a%22\);%0A++++assert_eq!\(err.value,+%22b%22\);%0A%7D&version=nightly&edition=2021)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#1160-1166)

####  pub fn  remove  <Q>(&mut self, k: [ &Q ](../primitive.reference.html) )
-> [ Option ](../option/enum.Option.html "enum std::option::Option") <V>

where K: [ Borrow ](../borrow/trait.Borrow.html "trait std::borrow::Borrow")
<Q>, Q: [ Hash ](../hash/trait.Hash.html "trait std::hash::Hash") \+ [ Eq
](../cmp/trait.Eq.html "trait std::cmp::Eq") \+ ? [ Sized
](../marker/trait.Sized.html "trait std::marker::Sized") ,

Removes a key from the map, returning the value at the key if the key was
previously in the map.

The key may be any borrowed form of the mapâs key type, but [ ` Hash `
](../hash/trait.Hash.html "trait std::hash::Hash") and [ ` Eq `
](../cmp/trait.Eq.html "trait std::cmp::Eq") on the borrowed form _must_ match
those for the key type.

#####  Â§  Examples

    use std::collections::HashMap;

    let mut map = HashMap::new();
    map.insert(1, "a");
    assert_eq!(map.remove(&1), Some("a"));
    assert_eq!(map.remove(&1), None);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+mut+map+=+HashMap::new\(\);%0A++++map.insert\(1,+%22a%22\);%0A++++assert_eq!\(map.remove\(%261\),+Some\(%22a%22\)\);%0A++++assert_eq!\(map.remove\(%261\),+None\);%0A%7D&edition=2021)

1.27.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#1189-1195)

####  pub fn  remove_entry  <Q>(&mut self, k: [ &Q
](../primitive.reference.html) ) -> [ Option ](../option/enum.Option.html
"enum std::option::Option") < [ (K, V) ](../primitive.tuple.html) >

where K: [ Borrow ](../borrow/trait.Borrow.html "trait std::borrow::Borrow")
<Q>, Q: [ Hash ](../hash/trait.Hash.html "trait std::hash::Hash") \+ [ Eq
](../cmp/trait.Eq.html "trait std::cmp::Eq") \+ ? [ Sized
](../marker/trait.Sized.html "trait std::marker::Sized") ,

Removes a key from the map, returning the stored key and value if the key was
previously in the map.

The key may be any borrowed form of the mapâs key type, but [ ` Hash `
](../hash/trait.Hash.html "trait std::hash::Hash") and [ ` Eq `
](../cmp/trait.Eq.html "trait std::cmp::Eq") on the borrowed form _must_ match
those for the key type.

#####  Â§  Examples

    use std::collections::HashMap;

    let mut map = HashMap::new();
    map.insert(1, "a");
    assert_eq!(map.remove_entry(&1), Some((1, "a")));
    assert_eq!(map.remove(&1), None);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Ause+std::collections::HashMap;%0A%0Afn+main\(\)+%7B%0Alet+mut+map+=+HashMap::new\(\);%0Amap.insert\(1,+%22a%22\);%0Aassert_eq!\(map.remove_entry\(%261\),+Some\(\(1,+%22a%22\)\)\);%0Aassert_eq!\(map.remove\(%261\),+None\);%0A%7D&edition=2021)

[ source ](../../src/std/collections/hash/map.rs.html#1198-1259) Â§

###  impl<K, V, S> [ HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>

where S: [ BuildHasher ](../hash/trait.BuildHasher.html "trait
std::hash::BuildHasher") ,

[ source ](../../src/std/collections/hash/map.rs.html#1235-1237)

####  pub fn  raw_entry_mut  (&mut self) -> [ RawEntryBuilderMut
](hash_map/struct.RawEntryBuilderMut.html "struct
std::collections::hash_map::RawEntryBuilderMut") <'_, K, V, S>

ð¬  This is a nightly-only experimental API. ( ` hash_raw_entry ` [ #56167
](https://github.com/rust-lang/rust/issues/56167) )

Creates a raw entry builder for the HashMap.

Raw entries provide the lowest level of control for searching and manipulating
a map. They must be manually initialized with a hash and then manually
searched. After this, insertions into a vacant entry still require an owned
key to be provided.

Raw entries are useful for such exotic situations as:

  * Hash memoization
  * Deferring the creation of an owned key until it is known to be required
  * Using a search key that doesnât work with the Borrow trait
  * Using custom comparison logic without newtype wrappers

Because raw entries provide much more low-level control, itâs much easier to
put the HashMap into an inconsistent state which, while memory-safe, will
cause the map to produce seemingly random results. Higher-level and more
foolproof APIs like ` entry ` should be preferred when possible.

In particular, the hash used to initialize the raw entry must still be
consistent with the hash of the key that is ultimately stored in the entry.
This is because implementations of HashMap may need to recompute hashes when
resizing, at which point only the keys are available.

Raw entries give mutable access to the keys. This must not be used to modify
how the key would compare or hash, as the map will not re-evaluate where the
key should go, meaning the keys may become âlostâ if their location does
not reflect their state. For instance, if you change a key so that the map now
contains keys which compare equal, search may start acting erratically, with
two keys randomly masking each other. Implementations are free to assume this
doesnât happen (within the limits of memory-safety).

[ source ](../../src/std/collections/hash/map.rs.html#1256-1258)

####  pub fn  raw_entry  (&self) -> [ RawEntryBuilder
](hash_map/struct.RawEntryBuilder.html "struct
std::collections::hash_map::RawEntryBuilder") <'_, K, V, S>

ð¬  This is a nightly-only experimental API. ( ` hash_raw_entry ` [ #56167
](https://github.com/rust-lang/rust/issues/56167) )

Creates a raw immutable entry builder for the HashMap.

Raw entries provide the lowest level of control for searching and manipulating
a map. They must be manually initialized with a hash and then manually
searched.

This is useful for

  * Hash memoization
  * Using a search key that doesnât work with the Borrow trait
  * Using custom comparison logic without newtype wrappers

Unless you are in such a situation, higher-level and more foolproof APIs like
` get ` should be preferred.

Immutable raw entries have very limited use; you might instead want `
raw_entry_mut ` .

##  Trait Implementations  Â§

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#1262-1277) Â§

###  impl<K, V, S> [ Clone ](../clone/trait.Clone.html "trait
std::clone::Clone") for [ HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>

where K: [ Clone ](../clone/trait.Clone.html "trait std::clone::Clone") , V: [
Clone ](../clone/trait.Clone.html "trait std::clone::Clone") , S: [ Clone
](../clone/trait.Clone.html "trait std::clone::Clone") ,

[ source ](../../src/std/collections/hash/map.rs.html#1269-1271) Â§

####  fn [ clone ](../clone/trait.Clone.html#tymethod.clone) (&self) -> Self

Returns a copy of the value. [ Read more
](../clone/trait.Clone.html#tymethod.clone)

[ source ](../../src/std/collections/hash/map.rs.html#1274-1276) Â§

####  fn [ clone_from ](../clone/trait.Clone.html#method.clone_from) (&mut
self, source: [ &Self ](../primitive.reference.html) )

Performs copy-assignment from ` source ` . [ Read more
](../clone/trait.Clone.html#method.clone_from)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#1305-1313) Â§

###  impl<K, V, S> [ Debug ](../fmt/trait.Debug.html "trait std::fmt::Debug")
for [ HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>

where K: [ Debug ](../fmt/trait.Debug.html "trait std::fmt::Debug") , V: [
Debug ](../fmt/trait.Debug.html "trait std::fmt::Debug") ,

[ source ](../../src/std/collections/hash/map.rs.html#1310-1312) Â§

####  fn [ fmt ](../fmt/trait.Debug.html#tymethod.fmt) (&self, f: &mut [
Formatter ](../fmt/struct.Formatter.html "struct std::fmt::Formatter") <'_>)
-> [ Result ](../fmt/type.Result.html "type std::fmt::Result")

Formats the value using the given formatter. [ Read more
](../fmt/trait.Debug.html#tymethod.fmt)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#1316-1325) Â§

###  impl<K, V, S> [ Default ](../default/trait.Default.html "trait
std::default::Default") for [ HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>

where S: [ Default ](../default/trait.Default.html "trait
std::default::Default") ,

[ source ](../../src/std/collections/hash/map.rs.html#1322-1324) Â§

####  fn [ default ](../default/trait.Default.html#tymethod.default) () -> [
HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>

Creates an empty ` HashMap<K, V, S> ` , with the ` Default ` value for the
hasher.

1.4.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#3159-3179) Â§

###  impl<'a, K, V, S> [ Extend ](../iter/trait.Extend.html "trait
std::iter::Extend") <( [ &'a K ](../primitive.reference.html) , [ &'a V
](../primitive.reference.html) )> for [ HashMap ](hash_map/struct.HashMap.html
"struct std::collections::hash_map::HashMap") <K, V, S>

where K: [ Eq ](../cmp/trait.Eq.html "trait std::cmp::Eq") \+ [ Hash
](../hash/trait.Hash.html "trait std::hash::Hash") \+ [ Copy
](../marker/trait.Copy.html "trait std::marker::Copy") , V: [ Copy
](../marker/trait.Copy.html "trait std::marker::Copy") , S: [ BuildHasher
](../hash/trait.BuildHasher.html "trait std::hash::BuildHasher") ,

[ source ](../../src/std/collections/hash/map.rs.html#3166-3168) Â§

####  fn [ extend ](../iter/trait.Extend.html#tymethod.extend) <T: [
IntoIterator ](../iter/trait.IntoIterator.html "trait
std::iter::IntoIterator") <Item = ( [ &'a K ](../primitive.reference.html) , [
&'a V ](../primitive.reference.html) )>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. [ Read more
](../iter/trait.Extend.html#tymethod.extend)

[ source ](../../src/std/collections/hash/map.rs.html#3171-3173) Â§

####  fn [ extend_one ](../iter/trait.Extend.html#method.extend_one) (&mut
self, (k, v): ( [ &'a K ](../primitive.reference.html) , [ &'a V
](../primitive.reference.html) ))

ð¬  This is a nightly-only experimental API. ( ` extend_one ` [ #72631
](https://github.com/rust-lang/rust/issues/72631) )

Extends a collection with exactly one element.

[ source ](../../src/std/collections/hash/map.rs.html#3176-3178) Â§

####  fn [ extend_reserve ](../iter/trait.Extend.html#method.extend_reserve)
(&mut self, additional: [ usize ](../primitive.usize.html) )

ð¬  This is a nightly-only experimental API. ( ` extend_one ` [ #72631
](https://github.com/rust-lang/rust/issues/72631) )

Reserves capacity in a collection for the given number of additional elements.
[ Read more ](../iter/trait.Extend.html#method.extend_reserve)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#3137-3156) Â§

###  impl<K, V, S> [ Extend ](../iter/trait.Extend.html "trait
std::iter::Extend") < [ (K, V) ](../primitive.tuple.html) > for [ HashMap
](hash_map/struct.HashMap.html "struct std::collections::hash_map::HashMap")
<K, V, S>

where K: [ Eq ](../cmp/trait.Eq.html "trait std::cmp::Eq") \+ [ Hash
](../hash/trait.Hash.html "trait std::hash::Hash") , S: [ BuildHasher
](../hash/trait.BuildHasher.html "trait std::hash::BuildHasher") ,

Inserts all new key-values from the iterator and replaces values with existing
keys with new values returned from the iterator.

[ source ](../../src/std/collections/hash/map.rs.html#3143-3145) Â§

####  fn [ extend ](../iter/trait.Extend.html#tymethod.extend) <T: [
IntoIterator ](../iter/trait.IntoIterator.html "trait
std::iter::IntoIterator") <Item = [ (K, V) ](../primitive.tuple.html) >>(&mut
self, iter: T)

Extends a collection with the contents of an iterator. [ Read more
](../iter/trait.Extend.html#tymethod.extend)

[ source ](../../src/std/collections/hash/map.rs.html#3148-3150) Â§

####  fn [ extend_one ](../iter/trait.Extend.html#method.extend_one) (&mut
self, (k, v): [ (K, V) ](../primitive.tuple.html) )

ð¬  This is a nightly-only experimental API. ( ` extend_one ` [ #72631
](https://github.com/rust-lang/rust/issues/72631) )

Extends a collection with exactly one element.

[ source ](../../src/std/collections/hash/map.rs.html#3153-3155) Â§

####  fn [ extend_reserve ](../iter/trait.Extend.html#method.extend_reserve)
(&mut self, additional: [ usize ](../primitive.usize.html) )

ð¬  This is a nightly-only experimental API. ( ` extend_one ` [ #72631
](https://github.com/rust-lang/rust/issues/72631) )

Reserves capacity in a collection for the given number of additional elements.
[ Read more ](../iter/trait.Extend.html#method.extend_reserve)

1.56.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#1360-1376) Â§

###  impl<K, V, const N: [ usize ](../primitive.usize.html) > [ From
](../convert/trait.From.html "trait std::convert::From") <[ [ (K, V)
](../primitive.tuple.html) ; [ N ](../primitive.array.html) ]> for [ HashMap
](hash_map/struct.HashMap.html "struct std::collections::hash_map::HashMap")
<K, V, [ RandomState ](hash_map/struct.RandomState.html "struct
std::collections::hash_map::RandomState") >

where K: [ Eq ](../cmp/trait.Eq.html "trait std::cmp::Eq") \+ [ Hash
](../hash/trait.Hash.html "trait std::hash::Hash") ,

[ source ](../../src/std/collections/hash/map.rs.html#1373-1375) Â§

####  fn [ from ](../convert/trait.From.html#tymethod.from) (arr: [ [ (K, V)
](../primitive.tuple.html) ; [ N ](../primitive.array.html) ]) -> Self

#####  Â§  Examples

    use std::collections::HashMap;

    let map1 = HashMap::from([(1, 2), (3, 4)]);
    let map2: HashMap<_, _> = [(1, 2), (3, 4)].into();
    assert_eq!(map1, map2);

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+map1+=+HashMap::from\(%5B\(1,+2\),+\(3,+4\)%5D\);%0A++++let+map2:+HashMap%3C_,+_%3E+=+%5B\(1,+2\),+\(3,+4\)%5D.into\(\);%0A++++assert_eq!\(map1,+map2\);%0A%7D&edition=2021)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#3122-3132) Â§

###  impl<K, V, S> [ FromIterator ](../iter/trait.FromIterator.html "trait
std::iter::FromIterator") < [ (K, V) ](../primitive.tuple.html) > for [
HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>

where K: [ Eq ](../cmp/trait.Eq.html "trait std::cmp::Eq") \+ [ Hash
](../hash/trait.Hash.html "trait std::hash::Hash") , S: [ BuildHasher
](../hash/trait.BuildHasher.html "trait std::hash::BuildHasher") \+ [ Default
](../default/trait.Default.html "trait std::default::Default") ,

[ source ](../../src/std/collections/hash/map.rs.html#3127-3131) Â§

####  fn [ from_iter ](../iter/trait.FromIterator.html#tymethod.from_iter) <T:
[ IntoIterator ](../iter/trait.IntoIterator.html "trait
std::iter::IntoIterator") <Item = [ (K, V) ](../primitive.tuple.html) >>(iter:
T) -> [ HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>

Creates a value from an iterator. [ Read more
](../iter/trait.FromIterator.html#tymethod.from_iter)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#1328-1345) Â§

###  impl<K, Q, V, S> [ Index ](../ops/trait.Index.html "trait
std::ops::Index") < [ &Q ](../primitive.reference.html) > for [ HashMap
](hash_map/struct.HashMap.html "struct std::collections::hash_map::HashMap")
<K, V, S>

where K: [ Eq ](../cmp/trait.Eq.html "trait std::cmp::Eq") \+ [ Hash
](../hash/trait.Hash.html "trait std::hash::Hash") \+ [ Borrow
](../borrow/trait.Borrow.html "trait std::borrow::Borrow") <Q>, Q: [ Eq
](../cmp/trait.Eq.html "trait std::cmp::Eq") \+ [ Hash
](../hash/trait.Hash.html "trait std::hash::Hash") \+ ? [ Sized
](../marker/trait.Sized.html "trait std::marker::Sized") , S: [ BuildHasher
](../hash/trait.BuildHasher.html "trait std::hash::BuildHasher") ,

[ source ](../../src/std/collections/hash/map.rs.html#1342-1344) Â§

####  fn [ index ](../ops/trait.Index.html#tymethod.index) (&self, key: [ &Q
](../primitive.reference.html) ) -> [ &V ](../primitive.reference.html)

Returns a reference to the value corresponding to the supplied key.

#####  Â§  Panics

Panics if the key is not present in the ` HashMap ` .

Â§

####  type [ Output ](../ops/trait.Index.html#associatedtype.Output) = V

The returned type after indexing.

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#2175-2184) Â§

###  impl<'a, K, V, S> [ IntoIterator ](../iter/trait.IntoIterator.html "trait
std::iter::IntoIterator") for &'a [ HashMap ](hash_map/struct.HashMap.html
"struct std::collections::hash_map::HashMap") <K, V, S>

Â§

####  type [ Item ](../iter/trait.IntoIterator.html#associatedtype.Item) = ( [
&'a K ](../primitive.reference.html) , [ &'a V ](../primitive.reference.html)
)

The type of the elements being iterated over.

Â§

####  type [ IntoIter
](../iter/trait.IntoIterator.html#associatedtype.IntoIter) = [ Iter
](hash_map/struct.Iter.html "struct std::collections::hash_map::Iter") <'a, K,
V>

Which kind of iterator are we turning this into?

[ source ](../../src/std/collections/hash/map.rs.html#2181-2183) Â§

####  fn [ into_iter ](../iter/trait.IntoIterator.html#tymethod.into_iter)
(self) -> [ Iter ](hash_map/struct.Iter.html "struct
std::collections::hash_map::Iter") <'a, K, V> â

Creates an iterator from a value. [ Read more
](../iter/trait.IntoIterator.html#tymethod.into_iter)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#2187-2196) Â§

###  impl<'a, K, V, S> [ IntoIterator ](../iter/trait.IntoIterator.html "trait
std::iter::IntoIterator") for &'a mut [ HashMap ](hash_map/struct.HashMap.html
"struct std::collections::hash_map::HashMap") <K, V, S>

Â§

####  type [ Item ](../iter/trait.IntoIterator.html#associatedtype.Item) = ( [
&'a K ](../primitive.reference.html) , [ &'a mut V
](../primitive.reference.html) )

The type of the elements being iterated over.

Â§

####  type [ IntoIter
](../iter/trait.IntoIterator.html#associatedtype.IntoIter) = [ IterMut
](hash_map/struct.IterMut.html "struct std::collections::hash_map::IterMut")
<'a, K, V>

Which kind of iterator are we turning this into?

[ source ](../../src/std/collections/hash/map.rs.html#2193-2195) Â§

####  fn [ into_iter ](../iter/trait.IntoIterator.html#tymethod.into_iter)
(self) -> [ IterMut ](hash_map/struct.IterMut.html "struct
std::collections::hash_map::IterMut") <'a, K, V> â

Creates an iterator from a value. [ Read more
](../iter/trait.IntoIterator.html#tymethod.into_iter)

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#2199-2226) Â§

###  impl<K, V, S> [ IntoIterator ](../iter/trait.IntoIterator.html "trait
std::iter::IntoIterator") for [ HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>

[ source ](../../src/std/collections/hash/map.rs.html#2223-2225) Â§

####  fn [ into_iter ](../iter/trait.IntoIterator.html#tymethod.into_iter)
(self) -> [ IntoIter ](hash_map/struct.IntoIter.html "struct
std::collections::hash_map::IntoIter") <K, V> â

Creates a consuming iterator, that is, one that moves each key-value pair out
of the map in arbitrary order. The map cannot be used after calling this.

#####  Â§  Examples

    use std::collections::HashMap;

    let map = HashMap::from([
        ("a", 1),
        ("b", 2),
        ("c", 3),
    ]);

    // Not possible with .iter()
    let vec: Vec<(&str, i32)> = map.into_iter().collect();

[ Run ](https://play.rust-
lang.org/?code=%23!%5Ballow\(unused\)%5D%0Afn+main\(\)+%7B%0A++++use+std::collections::HashMap;%0A++++%0A++++let+map+=+HashMap::from\(%5B%0A++++++++\(%22a%22,+1\),%0A++++++++\(%22b%22,+2\),%0A++++++++\(%22c%22,+3\),%0A++++%5D\);%0A++++%0A++++//+Not+possible+with+.iter\(\)%0A++++let+vec:+Vec%3C\(%26str,+i32\)%3E+=+map.into_iter\(\).collect\(\);%0A%7D&edition=2021)

Â§

####  type [ Item ](../iter/trait.IntoIterator.html#associatedtype.Item) = [
(K, V) ](../primitive.tuple.html)

The type of the elements being iterated over.

Â§

####  type [ IntoIter
](../iter/trait.IntoIterator.html#associatedtype.IntoIter) = [ IntoIter
](hash_map/struct.IntoIter.html "struct std::collections::hash_map::IntoIter")
<K, V>

Which kind of iterator are we turning this into?

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#1280-1293) Â§

###  impl<K, V, S> [ PartialEq ](../cmp/trait.PartialEq.html "trait
std::cmp::PartialEq") for [ HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>

where K: [ Eq ](../cmp/trait.Eq.html "trait std::cmp::Eq") \+ [ Hash
](../hash/trait.Hash.html "trait std::hash::Hash") , V: [ PartialEq
](../cmp/trait.PartialEq.html "trait std::cmp::PartialEq") , S: [ BuildHasher
](../hash/trait.BuildHasher.html "trait std::hash::BuildHasher") ,

[ source ](../../src/std/collections/hash/map.rs.html#1286-1292) Â§

####  fn [ eq ](../cmp/trait.PartialEq.html#tymethod.eq) (&self, other: & [
HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>) -> [ bool
](../primitive.bool.html)

This method tests for ` self ` and ` other ` values to be equal, and is used
by ` == ` .

1.0.0  Â· [ source ](https://doc.rust-
lang.org/1.80.1/src/core/cmp.rs.html#263) Â§

####  fn [ ne ](../cmp/trait.PartialEq.html#method.ne) (&self, other: [ &Rhs
](../primitive.reference.html) ) -> [ bool ](../primitive.bool.html)

This method tests for ` != ` . The default implementation is almost always
sufficient, and should not be overridden without very good reason.

1.0.0  Â· [ source ](../../src/std/collections/hash/map.rs.html#1296-1302) Â§

###  impl<K, V, S> [ Eq ](../cmp/trait.Eq.html "trait std::cmp::Eq") for [
HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>

where K: [ Eq ](../cmp/trait.Eq.html "trait std::cmp::Eq") \+ [ Hash
](../hash/trait.Hash.html "trait std::hash::Hash") , V: [ Eq
](../cmp/trait.Eq.html "trait std::cmp::Eq") , S: [ BuildHasher
](../hash/trait.BuildHasher.html "trait std::hash::BuildHasher") ,

1.36.0  Â· [ source ](../../src/std/panic.rs.html#82-88) Â§

###  impl<K, V, S> [ UnwindSafe ](../panic/trait.UnwindSafe.html "trait
std::panic::UnwindSafe") for [ HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>

where K: [ UnwindSafe ](../panic/trait.UnwindSafe.html "trait
std::panic::UnwindSafe") , V: [ UnwindSafe ](../panic/trait.UnwindSafe.html
"trait std::panic::UnwindSafe") , S: [ UnwindSafe
](../panic/trait.UnwindSafe.html "trait std::panic::UnwindSafe") ,

##  Auto Trait Implementations  Â§

Â§

###  impl<K, V, S> [ Freeze ](../marker/trait.Freeze.html "trait
std::marker::Freeze") for [ HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>

where S: [ Freeze ](../marker/trait.Freeze.html "trait std::marker::Freeze") ,

Â§

###  impl<K, V, S> [ RefUnwindSafe ](../panic/trait.RefUnwindSafe.html "trait
std::panic::RefUnwindSafe") for [ HashMap ](hash_map/struct.HashMap.html
"struct std::collections::hash_map::HashMap") <K, V, S>

where S: [ RefUnwindSafe ](../panic/trait.RefUnwindSafe.html "trait
std::panic::RefUnwindSafe") , K: [ RefUnwindSafe
](../panic/trait.RefUnwindSafe.html "trait std::panic::RefUnwindSafe") , V: [
RefUnwindSafe ](../panic/trait.RefUnwindSafe.html "trait
std::panic::RefUnwindSafe") ,

Â§

###  impl<K, V, S> [ Send ](../marker/trait.Send.html "trait
std::marker::Send") for [ HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>

where S: [ Send ](../marker/trait.Send.html "trait std::marker::Send") , K: [
Send ](../marker/trait.Send.html "trait std::marker::Send") , V: [ Send
](../marker/trait.Send.html "trait std::marker::Send") ,

Â§

###  impl<K, V, S> [ Sync ](../marker/trait.Sync.html "trait
std::marker::Sync") for [ HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>

where S: [ Sync ](../marker/trait.Sync.html "trait std::marker::Sync") , K: [
Sync ](../marker/trait.Sync.html "trait std::marker::Sync") , V: [ Sync
](../marker/trait.Sync.html "trait std::marker::Sync") ,

Â§

###  impl<K, V, S> [ Unpin ](../marker/trait.Unpin.html "trait
std::marker::Unpin") for [ HashMap ](hash_map/struct.HashMap.html "struct
std::collections::hash_map::HashMap") <K, V, S>

where S: [ Unpin ](../marker/trait.Unpin.html "trait std::marker::Unpin") , K:
[ Unpin ](../marker/trait.Unpin.html "trait std::marker::Unpin") , V: [ Unpin
](../marker/trait.Unpin.html "trait std::marker::Unpin") ,

##  Blanket Implementations  Â§

[ source ](https://doc.rust-lang.org/1.80.1/src/core/any.rs.html#140) Â§

###  impl<T> [ Any ](../any/trait.Any.html "trait std::any::Any") for T

where T: 'static + ? [ Sized ](../marker/trait.Sized.html "trait
std::marker::Sized") ,

[ source ](https://doc.rust-lang.org/1.80.1/src/core/any.rs.html#141) Â§

####  fn [ type_id ](../any/trait.Any.html#tymethod.type_id) (&self) -> [
TypeId ](../any/struct.TypeId.html "struct std::any::TypeId")

Gets the ` TypeId ` of ` self ` . [ Read more
](../any/trait.Any.html#tymethod.type_id)

[ source ](https://doc.rust-lang.org/1.80.1/src/core/borrow.rs.html#208) Â§

###  impl<T> [ Borrow ](../borrow/trait.Borrow.html "trait
std::borrow::Borrow") <T> for T

where T: ? [ Sized ](../marker/trait.Sized.html "trait std::marker::Sized") ,

[ source ](https://doc.rust-lang.org/1.80.1/src/core/borrow.rs.html#210) Â§

####  fn [ borrow ](../borrow/trait.Borrow.html#tymethod.borrow) (&self) -> [
&T ](../primitive.reference.html)

Immutably borrows from an owned value. [ Read more
](../borrow/trait.Borrow.html#tymethod.borrow)

[ source ](https://doc.rust-lang.org/1.80.1/src/core/borrow.rs.html#216) Â§

###  impl<T> [ BorrowMut ](../borrow/trait.BorrowMut.html "trait
std::borrow::BorrowMut") <T> for T

where T: ? [ Sized ](../marker/trait.Sized.html "trait std::marker::Sized") ,

[ source ](https://doc.rust-lang.org/1.80.1/src/core/borrow.rs.html#217) Â§

####  fn [ borrow_mut ](../borrow/trait.BorrowMut.html#tymethod.borrow_mut)
(&mut self) -> [ &mut T ](../primitive.reference.html)

Mutably borrows from an owned value. [ Read more
](../borrow/trait.BorrowMut.html#tymethod.borrow_mut)

[ source ](https://doc.rust-lang.org/1.80.1/src/core/convert/mod.rs.html#765)
Â§

###  impl<T> [ From ](../convert/trait.From.html "trait std::convert::From")
<T> for T

[ source ](https://doc.rust-lang.org/1.80.1/src/core/convert/mod.rs.html#768)
Â§

####  fn [ from ](../convert/trait.From.html#tymethod.from) (t: T) -> T

Returns the argument unchanged.

[ source ](https://doc.rust-
lang.org/1.80.1/src/core/convert/mod.rs.html#748-750) Â§

###  impl<T, U> [ Into ](../convert/trait.Into.html "trait
std::convert::Into") <U> for T

where U: [ From ](../convert/trait.From.html "trait std::convert::From") <T>,

[ source ](https://doc.rust-lang.org/1.80.1/src/core/convert/mod.rs.html#758)
Â§

####  fn [ into ](../convert/trait.Into.html#tymethod.into) (self) -> U

Calls ` U::from(self) ` .

That is, this conversion is whatever the implementation of ` [ From
](../convert/trait.From.html "trait std::convert::From") <T> for U ` chooses
to do.

[ source ](https://doc.rust-lang.org/1.80.1/src/alloc/borrow.rs.html#83-85) Â§

###  impl<T> [ ToOwned ](../borrow/trait.ToOwned.html "trait
std::borrow::ToOwned") for T

where T: [ Clone ](../clone/trait.Clone.html "trait std::clone::Clone") ,

Â§

####  type [ Owned ](../borrow/trait.ToOwned.html#associatedtype.Owned) = T

The resulting type after obtaining ownership.

[ source ](https://doc.rust-lang.org/1.80.1/src/alloc/borrow.rs.html#88) Â§

####  fn [ to_owned ](../borrow/trait.ToOwned.html#tymethod.to_owned) (&self)
-> T

Creates owned data from borrowed data, usually by cloning. [ Read more
](../borrow/trait.ToOwned.html#tymethod.to_owned)

[ source ](https://doc.rust-lang.org/1.80.1/src/alloc/borrow.rs.html#92) Â§

####  fn [ clone_into ](../borrow/trait.ToOwned.html#method.clone_into)
(&self, target: [ &mut T ](../primitive.reference.html) )

Uses borrowed data to replace owned data, usually by cloning. [ Read more
](../borrow/trait.ToOwned.html#method.clone_into)

[ source ](https://doc.rust-
lang.org/1.80.1/src/core/convert/mod.rs.html#805-807) Â§

###  impl<T, U> [ TryFrom ](../convert/trait.TryFrom.html "trait
std::convert::TryFrom") <U> for T

where U: [ Into ](../convert/trait.Into.html "trait std::convert::Into") <T>,

Â§

####  type [ Error ](../convert/trait.TryFrom.html#associatedtype.Error) = [
Infallible ](../convert/enum.Infallible.html "enum std::convert::Infallible")

The type returned in the event of a conversion error.

[ source ](https://doc.rust-lang.org/1.80.1/src/core/convert/mod.rs.html#812)
Â§

####  fn [ try_from ](../convert/trait.TryFrom.html#tymethod.try_from) (value:
U) -> [ Result ](../result/enum.Result.html "enum std::result::Result") <T, <T
as [ TryFrom ](../convert/trait.TryFrom.html "trait std::convert::TryFrom")
<U>>:: [ Error ](../convert/trait.TryFrom.html#associatedtype.Error "type
std::convert::TryFrom::Error") >

Performs the conversion.

[ source ](https://doc.rust-
lang.org/1.80.1/src/core/convert/mod.rs.html#790-792) Â§

###  impl<T, U> [ TryInto ](../convert/trait.TryInto.html "trait
std::convert::TryInto") <U> for T

where U: [ TryFrom ](../convert/trait.TryFrom.html "trait
std::convert::TryFrom") <T>,

Â§

####  type [ Error ](../convert/trait.TryInto.html#associatedtype.Error) = <U
as [ TryFrom ](../convert/trait.TryFrom.html "trait std::convert::TryFrom")
<T>>:: [ Error ](../convert/trait.TryFrom.html#associatedtype.Error "type
std::convert::TryFrom::Error")

The type returned in the event of a conversion error.

[ source ](https://doc.rust-lang.org/1.80.1/src/core/convert/mod.rs.html#797)
Â§

####  fn [ try_into ](../convert/trait.TryInto.html#tymethod.try_into) (self)
-> [ Result ](../result/enum.Result.html "enum std::result::Result") <U, <U as
[ TryFrom ](../convert/trait.TryFrom.html "trait std::convert::TryFrom")
<T>>:: [ Error ](../convert/trait.TryFrom.html#associatedtype.Error "type
std::convert::TryFrom::Error") >

Performs the conversion.


Question:
Type of an object that contains CSS properties

I have a function that takes an element on the page and adds CSS to its style attribute. I want the argument that is passed to it to be an object with keys such as height, minWidth, flexDirection, etc.

```
function addStyle (el: HTMLElement, style: Style): void {
  for (const property in style) {
    el.style[property] = style[property]
  }
}
```

My problem is in typing this object. It's obviously not feasible to define every single CSS property myself. I'm pretty sure that TypeScript should be able to do this itself, I'm just not sure how. This is my best guess:
```
type Style = Partial<CSSStyleDeclaration>
```

...but that results in the error "Type 'string | undefined' is not assignable to type 'string'"

That specific error can be easily overridden, but I'm wary that it indicates I'm doing something wrong or unintuitive.

Is there a standard way to type an object that contains CSS properties?

Explanation: Because there might be multiple data in CSS that corresponds to different data types, such as height, minWidth, and so on. One solution is needed to use the language tools and built-in types provided by TypeScript and construct a new type definition that covers all CSS property names. Instead of declaring types one by one.

I don't think there's a good way to do this sort of thing, When typing a
property that may or may not exist on an object, TypeScript does not
differentiate between the property existing and containing the value `
undefined ` , and the property not existing at all.

For example, disregarding styles and everything else, consider typing an object which may have the ` foo ` property which is a string. You can't do ` { foo: string } ` because the property may not exist. You can do ` { foo: string | undefined } ` . You can also do ` { foo?: string } ` , but this type is identical to the previous one. I don't think there are any other options: you can't say "This property may or may not exist, but if it does exist, it does not contain ` undefined ` ."

A CSSStyleDeclaration is the same sort of situation, except with lots more
properties. ` Partial<CSSStyleDeclaration> ` is the right way to go, but
unfortunately, since TypeScript won't distinguish between partial types having
properties containing ` undefined ` and not having those properties at all,
you have to assert that the value _does_ exist, if dealing with an individual
value

But, there's another way to bypass having to reference and assert individual
values, which is to use ` Object.assign ` :

    type Style = Partial<CSSStyleDeclaration>;
    function addStyle(el: HTMLElement, style: Style) {
        Object.assign(el.style, style);
    }

(also remember that there's no need to specify the return type of a function
if TS can determine it automatically - less code to read and write is usually
a good thing)


Question:
Docker Swarm with image versions externalized to .env file

I used to externalized my image versions to my .env file. This make it easy to maintain and I don't modify my docker-compose.yml file just to upgrade a version, so I'm sure I won't delete a line by mistake or whatever.

But when I try to deploy my services with stack to the swarm, docker engine complains that my image is not a correct reposity/tag, with the exact following message :

```
Error response from daemon: rpc error: code = 3 desc = ContainerSpec: "GROUP/IMAGE:" is not a valid repository/tag
```

To fix this, I can fix the image version directly in the docker-compose.yml file. Is there any logic here or it that a bug? But this mixes fix part of the docker-compose and variable ones.

Cheers, Olivier

Explanation:
The problem of not being able to read the image version information from the .env file when deploying in Docker Swarm is actually due to the difference in parsing capabilities between Swarm's yaml parser and docker-compose.
We need a way to solve this compatibility problem. It would be better to allow the continued use of .env files to store variable information such as image versions, while also meeting the requirements of Swarm deployments, thus achieving versioning flexibility and maintainability.

The yaml parser in ` docker stack deploy ` doesn't have all the same features
of that in ` docker-compose ` . However, you can use ` docker-compose config `
to output a yaml file after it's done all the variable substitutions,
extending other files, and merging multiple files together. This effectively
turns ` docker-compose ` into a preprocessor.