Search⌘ K
AI Features

Storing a Variable Amount of Data with Vectors

Explore how to manage dynamic data in Rust using vectors instead of fixed-size arrays. Learn to add elements with push, handle user input in loops, and print complex structures with the Debug trait. This lesson deepens your ability to manipulate growing collections efficiently while maintaining code clarity.

Instead of turning people who aren’t on the visitor list away, we decide to let them in and store their names for the next party.

Arrays can’t change size, but Vectors (Vec) are designed to be dynamically resizable. They can be used as arrays, but we can add to them with a method named push(). Vectors can keep growing, limited only by the size of your computer’s memory.

Deriving debug

When we were just storing names as strings, printing them was easy; send them to println! and we’re done. We want to be able to print the contents of a Visitor structure.

The debug placeholders ({:?} for raw printing and {:#?} for pretty printing) print any type that supports the Debug trait. Adding debug support to our Visitor structure is easy and makes use of another convenient feature Rust: the derive macro.

Rust 1.40.0
#[derive(Debug)]
struct Visitor {
name: String,
greeting: String
}

The ...