Rust Structs: A Fun Guide with Examples
A fun but comprehensive guide for Structs in Rust with metaphors from The Game of Thrones.
Published in
5 min readFeb 26, 2024
Welcome to the royal world of Rust. I will explain all about Structs, drawing parallels with Game of Thrones to make the journey fun while keeping it practical at the same time.
You can practice the code snippets from this article on Rust Drills.
1. The Basics of Structs
When we want to group related values, structs come really handy.
For example, we can define each great house in the Game of Thrones with some specific attributes, such as name and region.
struct House {
name: String,
region: String,
}
fn main() {
let house_stark = House {
name: String::from("Stark"),
region: String::from("The North"),
};
println!("House {} of {}", house_stark.name, house_stark.region);
}
We defined a noble house in Westeros as a House
struct with fields for name
and region
.
2. Methods in Structs
Each house has a specific way it behaves in certain situations. Let’s say that each house can rally its bannermen for aid.