Vec
Vec
is the standard resizable heap-allocated buffer:
Vec
implements Deref<Target = [T]>
, which means that you can call slice methods on a Vec
.
Speaker Notes
This slide should take about 5 minutes.
Vec
is a type of collection, along withString
andHashMap
. The data it contains is stored on the heap. This means the amount of data doesn't need to be known at compile time. It can grow or shrink at runtime.- Notice how
Vec<T>
is a generic type too, but you don't have to specifyT
explicitly. As always with Rust type inference, theT
was established during the firstpush
call. vec![...]
is a canonical macro to use instead ofVec::new()
and it supports adding initial elements to the vector.- To index the vector you use
[
]
, but they will panic if out of bounds. Alternatively, usingget
will return anOption
. Thepop
function will remove the last element. - Slices are covered on day 3. For now, students only need to know that a value of type
Vec
gives access to all of the documented slice methods, too.