Vectors: A Growing List
Imagine a backpack that grows a little bigger every time you add something. π You can keep packing in books, snacks, and water bottles, and it never runs out of room. In Rust, that ever-expanding backpack is called a vector.
Vec<T>) is a list that can
grow. You can keep adding items one at a time, and Rust makes room
for each new thing.
Making a backpack
The fastest way to start a vector is with the vec! helper. The T in
Vec<T> just means βthe type of thing insideβ β like Vec<i32> for whole numbers.
Adding more with .push()
To put a new item in the backpack, you use .push(). To look at one item, use
square brackets like v[0] (remember, counting starts at 0). To visit every
item, you loop with for x in &v.
The little word mut means the bag is allowed to change. Without it, Rust
would keep the backpack zipped shut! π
& in for x in &bag
means "just borrow a peek" β you look at each item without taking it out of the bag.
bag.push(50); line, then press βΆ Run. Watch
the total grow!
Quick quiz
How do you add a new item to the end of a vector?
Yes! .push() stuffs a new item into your growing backpack. π
vec![],
add to it with .push(), read items with v[0], and loop with
for x in &v. Next up: holding words and sentences with
Strings! π€