Vectors of Structs
Hold complex data in a Vec.
Vectors of Structs is a free Learn Rust Coding lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Vectors of Structs
Vectors can hold any single type, including your own structs. A Vec<Person> stores many people in order, which is great for lists of records like users, items, or scores.
This combines custom data shapes with a growable list.
Defining a Struct
First define the struct you want to store. This Person has a name and an age.
The #[derive(Debug)] line lets us print a person with {:?}, which is useful for whole vectors.
#[derive(Debug)]
struct Person {
name: String,
age: u32,
}Building the Vector
Create instances of the struct, then collect them in a vec! macro. The vector's type becomes Vec<Person> automatically.
Use {:?} to print all the records at once.
#[derive(Debug)]
struct Person { name: String, age: u32 }
fn main() {
let people = vec![
Person { name: String::from("Ann"), age: 30 },
Person { name: String::from("Bo"), age: 25 },
];
println!("{:?}", people);
}Pushing Structs
You can also start empty and push structs one by one. The vector must be mut to grow.
This pattern fits when records arrive over time, such as from user input.
#[derive(Debug)]
struct Item { name: String }
fn main() {
let mut cart = Vec::new();
cart.push(Item { name: String::from("Pen") });
cart.push(Item { name: String::from("Mug") });
println!("{:?}", cart);
}Looping Over Records
Loop over &people to read each struct without taking ownership. Inside the loop you reach fields with dot notation, like p.name.
This prints a friendly line for every record.
#[derive(Debug)]
struct Person { name: String, age: u32 }
fn main() {
let people = vec![
Person { name: String::from("Ann"), age: 30 },
Person { name: String::from("Bo"), age: 25 },
];
for p in &people {
println!("{} is {}", p.name, p.age);
}
}Reading One Field
Index into the vector to reach one struct, then use dot notation for its field. So people[0].name gives the first person's name.
Remember indexes start at 0 and out-of-range access panics.
#[derive(Debug)]
struct Person { name: String, age: u32 }
fn main() {
let people = vec![
Person { name: String::from("Ann"), age: 30 },
];
println!("name: {}", people[0].name);
}Changing a Field
To edit a record, the vector must be mut. Then index to the struct and assign to its field, like people[0].age = 31.
This updates the stored data in place.
struct Person { name: String, age: u32 }
fn main() {
let mut people = vec![
Person { name: String::from("Ann"), age: 30 },
];
people[0].age = 31;
println!("{}", people[0].age);
}Summing a Field
Iterators can pull one field from every record. Here iter().map(|p| p.age).sum() adds up all the ages.
The map step turns each person into just an age before summing.
struct Person { name: String, age: u32 }
fn main() {
let people = vec![
Person { name: String::from("Ann"), age: 30 },
Person { name: String::from("Bo"), age: 20 },
];
let total: u32 = people.iter().map(|p| p.age).sum();
println!("total age = {}", total);
}Filtering Records
Use iter().filter(...) to keep records that match a rule. The closure returns a bool for each struct.
Here we count how many people are at least 30 years old.
struct Person { name: String, age: u32 }
fn main() {
let people = vec![
Person { name: String::from("Ann"), age: 30 },
Person { name: String::from("Bo"), age: 20 },
];
let adults = people.iter().filter(|p| p.age >= 30).count();
println!("adults: {}", adults);
}Sorting by a Field
Sort records by a field with sort_by_key. Give it a closure that returns the value to order by, such as the age.
The vector must be mut because sorting rearranges it.
#[derive(Debug)]
struct Person { name: String, age: u32 }
fn main() {
let mut people = vec![
Person { name: String::from("Ann"), age: 30 },
Person { name: String::from("Bo"), age: 20 },
];
people.sort_by_key(|p| p.age);
println!("{:?}", people);
}Counting Records
The number of stored structs is simply len(), just like any vector. This tells you how many records you currently hold.
Pair it with is_empty() to guard before reading the first record.
struct Item { name: String }
fn main() {
let cart = vec![
Item { name: String::from("Pen") },
Item { name: String::from("Mug") },
];
println!("items: {}", cart.len());
}Quick Check
Test your understanding of vectors of structs.
Recap
You stored structs in a Vec, built it with vec! and push, and read or edited fields by index and in loops.
You also summed, filtered, sorted by a field, and counted records. You can now manage lists of structured data with vectors.
Frequently asked questions
Is the “Vectors of Structs” lesson free?
Yes — the full text of “Vectors of Structs” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “Vectors of Structs”?
Hold complex data in a Vec. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Vectors of Structs” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Creating and Filling Vectors
- Indexing and Iterating
- Growing and Shrinking
- Vectors of Structs