

RUST Map Object
In RUST, The type HashMapTo create a new Map (HashMap) object in RUST we use std::collections::HashMap library.
Example of creating Map Object
use std::collections::HashMap;
fn main() {
let solar_distance = HashMap::from([
("Mercury", 0.4),
("Venus", 0.7),
("Earth", 1.0),
("Mars", 1.5),
]);
}
RUST Iterate through Elements in Map Objects
Below example shows how we can iterate through elements in a Mapuse std::collections::HashMap;
fn main() {
let solar_distance = HashMap::from([
("Mercury", 0.4),
("Venus", 0.7),
("Earth", 1.0),
("Mars", 1.5),
]);
for (key, value) in &solar_distance {
println!("{}: \"{}\"", key, value);
}
}
Output
Venus: "0.7"
Earth: "1"
Mercury: "0.4"
Mars: "1.5"
Earth: "1"
Mercury: "0.4"
Mars: "1.5"
RUST Iterate through Elements in Map Objects
Below example shows how we can iterate through elements in a Mapuse std::collections::HashMap;
fn main() {
let solar_distance = HashMap::from([
("Mercury", 0.4),
("Venus", 0.7),
("Earth", 1.0),
("Mars", 1.5),
]);
for (key, value) in &solar_distance {
println!("{}: \"{}\"", key, value);
}
}
Output
Venus: "0.7"
Earth: "1"
Mercury: "0.4"
Mars: "1.5"
Earth: "1"
Mercury: "0.4"
Mars: "1.5"
RUST get exact element value in Map Objects
Below example shows how we can get an exact element in a RUST Mapuse std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert(1, "Jhon");
map.insert(5, "William");
println!("Name of key needed is {}", map.get(&5).unwrap());
}
Output
Name of key needed is William
Conclusion
In this page (written and validated by A. Gawali) you learned about Rust Map Object - HashMap . What's Next? If you are interested in completing Rust tutorial, your next topic will be learning about: Rust Enum.
Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.
Share On: |
Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.