6 More collections, more error handling

 

This chapter covers

  • Other collections—more complex and interesting ones this time
  • The question mark operator—just type ? to handle errors
  • When panic and unwrap are good

Rust has a lot more collection types than the ones we learned in chapter 3. You might not need all of them right away, but be sure to give each collection type a read so that you’ll remember when you might need each one of them. This chapter also introduces one of Rust’s most loved operators: ? (Yes, it’s just a question mark.)

6.1 Other collections

Rust has many more types of collections besides the ones we learned in chapter 3. All of them are contained in the same spot: the std::collections module in the standard library. The best way to use them is to bring them into scope with a use statement, like we did with our enums in the last chapter. The page for the collections module (http://mng.bz/27yd) on the standard library has a really nice summary of when to use which collection type and for what reasons, so be sure to bookmark it.

We will start with HashMap, which is extremely common.

6.1.1 HashMap (and BTreeMap)

A HashMap is a collection made out of keys and values. You use the key to look up the value that matches the key. An example of a key and a value is email and my_email@ .address.com (email is the key; the address is the value).

Creating a new HashMap is easy: you can just use HashMap::new(). After that, you can use the .insert(key, value) method to insert items.

6.1.2 HashSet and BTreeSet

6.1.3 BinaryHeap

6.1.4 VecDeque

6.2 The ? operator

6.3 When panic and unwrap are good

Summary

sitemap