Storing a Variable Amount of Data with Vectors
Hands-on Rust — by Herbert Wolverson (29 / 120)
👈 Grouping Data with Structs | TOC | Categorizing with Enumerations 👉
Instead of turning away people who aren’t on the visitor list, you decide to let them in and store their names for the next party.
Arrays can’t change size. Vectors (Vec) are designed to be dynamically resizable. They can be used like arrays, but you can add to them with a method named push.[29] Vectors can keep growing — you are limited only by the size of your computer’s memory.
Deriving Debug
When you were just storing names as strings, printing them was easy. Send them to println! and you’re done. You 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 your Visitor structure is easy, and makes use of another convenient feature of Rust: the derive macro.
FirstStepsWithRust/treehouse_guestlist_vector/src/main.rs
#[derive(Debug)]
struct Visitor {
name: String,
greeting: String
}
Derive macros are a very powerful mechanism to save you from typing repetitive boilerplate code. You can derive a lot of things — you’ll use derive statements regularly throughout the book. Deriving requires that every member field in…