]> git.lizzy.rs Git - rust.git/commitdiff
std::hashmap: add an example with the basic methods.
authorHuon Wilson <dbau.pp+github@gmail.com>
Fri, 27 Dec 2013 11:36:02 +0000 (22:36 +1100)
committerHuon Wilson <dbau.pp+github@gmail.com>
Sat, 28 Dec 2013 23:32:56 +0000 (10:32 +1100)
src/libstd/hashmap.rs

index e93a76e5556ca1bb6b93f8eca4e7d0ad4ea0e38a..03956560db939bc788dc7ed66283d300a05e795e 100644 (file)
 //!
 //! The tables use a keyed hash with new random keys generated for each container, so the ordering
 //! of a set of keys in a hash table is randomized.
+//!
+//! # Example
+//!
+//! ```rust
+//! use std::hashmap::HashMap;
+//!
+//! // type inference lets us omit an explicit type signature (which
+//! // would be `HashMap<&str, &str>` in this example).
+//! let mut book_reviews = HashMap::new();
+//!
+//! // review some books.
+//! book_reviews.insert("Adventures of Hucklebury Fin",      "My favorite book.");
+//! book_reviews.insert("Grimms' Fairy Tales",               "Masterpiece.");
+//! book_reviews.insert("Pride and Prejudice",               "Very enjoyable.");
+//! book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");
+//!
+//! // check for a specific one.
+//! 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.iter() {
+//!     match book_reviews.find(book) {
+//!         Some(review) => println!("{}: {}", *book, *review),
+//!         None => println!("{} is unreviewed.", *book)
+//!     }
+//! }
+//!
+//! // iterate over everything.
+//! for (book, review) in book_reviews.iter() {
+//!     println!("{}: \"{}\"", *book, *review);
+//! }
+//! ```
 
 use container::{Container, Mutable, Map, MutableMap, Set, MutableSet};
 use clone::Clone;