Skip to content

Commit 8715736

Browse files
committed
std::hashmap: add an example with the basic methods.
1 parent 2ca0b58 commit 8715736

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/libstd/hashmap.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,45 @@
1212
//!
1313
//! The tables use a keyed hash with new random keys generated for each container, so the ordering
1414
//! of a set of keys in a hash table is randomized.
15+
//!
16+
//! # Example
17+
//!
18+
//! ```rust
19+
//! use std::hashmap::HashMap;
20+
//!
21+
//! // type inference lets us omit an explicit type signature (which
22+
//! // would be `HashMap<&str, &str>` in this example).
23+
//! let mut book_reviews = HashMap::new();
24+
//!
25+
//! // review some books.
26+
//! book_reviews.insert("Adventures of Hucklebury Fin", "My favorite book.");
27+
//! book_reviews.insert("Grimms' Fairy Tales", "Masterpiece.");
28+
//! book_reviews.insert("Pride and Prejudice", "Very enjoyable.");
29+
//! book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");
30+
//!
31+
//! // check for a specific one.
32+
//! if !book_reviews.contains_key(& &"Les Misérables") {
33+
//! println!("We've got {} reviews, but Les Misérables ain't one.",
34+
//! book_reviews.len());
35+
//! }
36+
//!
37+
//! // oops, this review has a lot of spelling mistakes, let's delete it.
38+
//! book_reviews.remove(& &"The Adventures of Sherlock Holmes");
39+
//!
40+
//! // look up the values associated with some keys.
41+
//! let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
42+
//! for book in to_find.iter() {
43+
//! match book_reviews.find(book) {
44+
//! Some(review) => println!("{}: {}", *book, *review),
45+
//! None => println!("{} is unreviewed.", *book)
46+
//! }
47+
//! }
48+
//!
49+
//! // iterate over everything.
50+
//! for (book, review) in book_reviews.iter() {
51+
//! println!("{}: \"{}\"", *book, *review);
52+
//! }
53+
//! ```
1554
1655
use container::{Container, Mutable, Map, MutableMap, Set, MutableSet};
1756
use clone::Clone;

0 commit comments

Comments
 (0)