πŸ“‹
World 8 Β· Collections

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.

The Big Idea A vector (written 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.

Think of it like this… A vector is a row of labeled cubbies. The first cubby is number 0, the next is 1, and so on. Rust starts counting at zero!

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! πŸ”’

Ferris says: The & in for x in &bag means "just borrow a peek" β€” you look at each item without taking it out of the bag.
Try this! Add another 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. πŸŽ’

You learned… A vector is a growing list. You build one with 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! πŸ”€