In this lesson, you will learn how to create your own custom data types using structs to model real-world concepts with precision and safety.
Modeling with Named Fields
So far, you have used primitive types like integers and strings. But what if you want to represent something like a User? You could use a tuple, but keeping track of whether the first element is the ID or the email address becomes confusing quickly.
A struct (short for structure) lets you bundle related data together, giving each piece a descriptive name. This creates a "named record" that documents your code automatically.
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
By defining this structure, you’ve created a new custom type. You can now instantiate it like this:
let user1 = User {
username: String::from("rustacean"),
email: String::from("learn@rust.com"),
sign_in_count: 1,
active: true,
};
Unit Structs for Type Safety
Sometimes, you don’t need to store data inside a struct; you just need to distinguish between different "tags" or "markers." This is where unit structs come in. They have no fields and are defined without curly braces.
struct AlwaysValid;
Why use these? They are useful when you want to use the type system to enforce rules. For example, if you are working on a game, you might define struct Player; and struct Enemy;. Even though they hold no data, Rust will prevent you from accidentally passing an Enemy into a function that expects a Player. This provides compile-time safety without the overhead of storing extra variables.
Why This Matters
By defining custom structs, you transform raw data into a structured domain model. Instead of passing around loose variables, you pass around objects that represent the "truth" of your application. The compiler then ensures you only ever interact with your data in the ways you explicitly intended.
Key Takeaway: Structs allow you to create custom types that group data logically with named fields or act as distinct markers via unit structs, significantly increasing your code's clarity and safety.