Working with collections
Nearly every program is a loop over a collection with something counted, sorted or looked up.
This chapter is that work: the Vec operations you will actually use, the entry API on a
HashMap, and a decision table for when the answer is not Vec.
Start with the decision table if you are choosing, or with the specific error if you already have one.
Articles
Section titled “Articles”- Which collection should you use?a decision table for Vec, HashMap, BTreeMap, HashSet
- How to get an element from a Vec without panickingget() returns an Option, [] does not
- Why can’t I modify a Vec while iterating over it?retain, drain, and collecting first
- What is the difference between a Vec and a slice?who owns the buffer
- How to accept both a Vec and a slice in one functiontake &[T] and stop cloning at the call site
- How to sort a Vecsort, sort_by, and sort_unstable
- How to sort a Vec of structs by a fieldsort_by_key, and the borrow that gets in the way
- How to deduplicate a Vecdedup needs sorted input, and the alternative
- How to find an element in a Veciter().find, and the position you probably wanted
- How to split a Vec into chunkschunks, chunks_exact, and the short last one
- Why can’t I use f64 as a HashMap key?NaN breaks the contract, so Eq is not implemented
- How to handle missing keys with the entry APIentry().or_insert() and friends
- What is the difference between HashMap and BTreeMap?sorted iteration versus speed
- How to check whether a collection contains a valueHashSet versus a linear scan
- Why is a HashMap’s order different every run?unordered by design, and how to get a stable order anyway
- How to count word frequency with a HashMapthe entry API on a real problem
- How to use a Vec as a queueVecDeque, and why remove(0) is the wrong tool
- How to get the largest element from a collectionBinaryHeap, and when max() is enough
- Why does indexing an array out of bounds panic?the bounds check, and get()
- What is the difference between an array and a Vec?fixed on the stack versus growable on the heap
- How to tell the compiler the type of an empty Vecthe turbofish, and the annotation that reads better
- How to store different types in one Vecan enum with data in each variant
- How to use itertools for iterator helpersthe adapters the standard library does not have