I'm trying to set a constant, predefined hash map in Rust. I'm not sure what the best practice is in Rust for this.
use std::collections::HashMap;
pub const Countries: HashMap<&str, &str> = [
("UK", "United Kingdom"),
("US", "United States")
].iter().cloned().collect();
These will then be referenced later in the library.
If this is bad, I'm guessing a match in a function is the best way?
HashMap uses a slow (cryptographic) hasher by default; you can do better by swapping it out for a fast one.
HashMap s are inherently unordered collections, and BTree s are inherently ordered by their keys.
Starting with Rust 1.56, you can use from() to build a Hashmap from an array of key-value pairs. This makes it possible to initialize concisely without needing to specify types or write macros.
To access values from HashMap using keys: Import HashMap. Insert records in HashMap. Use get( & key) for getting the value.
There are many operations for Rust HashMap execution like insertion, removal, iteration, addition, and many more. The key and value present within the hash table helps in one or the other way in taking decision regarding the accessibility of elements. HashMap uses hashing algorithm which is selected for providing resistance against HashDos attack.
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.
The hash map is initially created with a capacity of 0, so it will not allocate until it is first inserted into. 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.
The default hashing algorithm is currently SipHash 1-3, though this is subject to change at any point in the future.
You can use https://crates.io/crates/lazy_static (lazily executed at runtime).
I personally use https://crates.io/crates/phf (compile-time static collections) for this if the data is truly static.
use phf::{phf_map};
static COUNTRIES: phf::Map<&'static str, &'static str> = phf_map! {
"US" => "United States",
"UK" => "United Kingdom",
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With