Skip to main content

EntryRef

Enum EntryRef 

Source
pub enum EntryRef<'a, 'b, K, Q, V, S, A = Global>
where A: Allocator, Q: ?Sized,
{ Occupied(OccupiedEntryRef<'a, 'b, K, Q, V, S, A>), Vacant(VacantEntryRef<'a, 'b, K, Q, V, S, A>), }
Expand description

A view into a single entry in a map, which may either be vacant or occupied, with any borrowed form of the map’s key type.

This enum is constructed from the entry_ref method on HashMap.

Hash and Eq on the borrowed form of the map’s key type must match those for the key type. It also require that key may be constructed from the borrowed form through the From trait.

§Examples

use rune::alloc::prelude::*;
use rune::alloc::hash_map::{EntryRef, HashMap, OccupiedEntryRef};

let mut map = HashMap::new();
map.try_extend([
    ("a".try_to_owned()?, 10),
    ("b".try_to_owned()?, 20),
    ("c".try_to_owned()?, 30)
])?;

assert_eq!(map.len(), 3);

// Existing key (try_insert)
let key = String::try_from("a")?;
let entry: EntryRef<_, _, _, _> = map.entry_ref(&key);
let _raw_o: OccupiedEntryRef<_, _, _, _> = entry.try_insert(1)?;
assert_eq!(map.len(), 3);
// Nonexistent key (try_insert)
map.entry_ref("d").try_insert(4)?;

// Existing key (or_try_insert)
let v = map.entry_ref("b").or_try_insert(2)?;
assert_eq!(std::mem::replace(v, 2), 20);
// Nonexistent key (or_try_insert)
map.entry_ref("e").or_try_insert(5)?;

// Existing key (or_try_insert_with)
let v = map.entry_ref("c").or_try_insert_with(|| 3)?;
assert_eq!(std::mem::replace(v, 3), 30);
// Nonexistent key (or_try_insert_with)
map.entry_ref("f").or_try_insert_with(|| 6)?;

println!("Our HashMap: {:?}", map);

for (key, value) in ["a", "b", "c", "d", "e", "f"].into_iter().zip(1..=6) {
    assert_eq!(map[key], value)
}
assert_eq!(map.len(), 6);

Variants§

§

Occupied(OccupiedEntryRef<'a, 'b, K, Q, V, S, A>)

An occupied entry.

§Examples

use rune::alloc::hash_map::{EntryRef, HashMap};
let mut map: HashMap<_, _> = [("a".to_owned(), 100), ("b".into(), 200)].try_into()?;

match map.entry_ref("a") {
    EntryRef::Vacant(_) => unreachable!(),
    EntryRef::Occupied(_) => { }
}
§

Vacant(VacantEntryRef<'a, 'b, K, Q, V, S, A>)

A vacant entry.

§Examples

use rune::alloc::hash_map::{EntryRef, HashMap};
let mut map: HashMap<String, i32> = HashMap::new();

match map.entry_ref("a") {
    EntryRef::Occupied(_) => unreachable!(),
    EntryRef::Vacant(_) => { }
}