Collections
Arrays
Arrays are placed on the stack, since their size is static and always needs to be predefined.
Iterator is returned with countries.iter();
.
Array is typed like this: [u32, 5]
- 5 elements of type u32
.
Each array with different type and size is like a separate type in Rust.
Vectors
Another collection type. It’s dynamic, so it’s placed on the heap (it’s a
struct). Vec<T>
is like a List<T>
in C#. They are more expensive than
arrays. Elements are placed next to each other in memory.
Creating vectors:
Operations on vectors:
The second way of reading will not panic if we try to access element out of
index. It will return Option.None
instead.
HashMaps
Iterators
Iterators give access to consecutive elements in collections. Iterators
implement the Iterator
trait, which exposes next()
method and Item
.
It’s easy to define our own iterators.
Iterators provide zero-cost abstractions, they are very performant.
There are three methods on collections that return iterators:
iter()
- iterates over immutable references to items in the collectioniter_mut()
- iterates over mutable references to items in the collectioninto_iter()
- returns owned values from the collection
Consuming Adaptors
Some methods defined on the Iterator
trait take ownership of the iterator
and return something useful. An example is the sum()
method.
Collect Function
The collect()
function consumes iterator into an actual collection
of values.
It also has a specific implementation that can turn an Iterator<Result<T>>
into a
Result<Vec<T>>
(so it kind of reverses the outer layers).
collect
is one of cases where we often need to provide the expected output type in cases where
various outputs are possible.
Iterator Adaptors
Some other methods can transform an iterator into another kind of iterator. These iterators are lazy, so to actually do anything the resulting iterator needs to be consumed.
Examples:
map()
- takes a closure to be executed agains each item and returns closure’s result. It’s similar to JS’smap
in concept.filter()
- returns an iterator that filters source collection based on a closure returning bool.skip()
- skips some items.