In our last session, we mastered Rust's borrowing system, learning how to use shared (&) and mutable (&mut) references to access data without taking ownership. This powerful mechanism, enforced by the borrow checker, is a cornerstone of writing safe and efficient Rust code.
Today, we'll build upon that foundation by learning how to create our own custom, complex data types. While primitive types like integers and booleans are useful, most real-world applications require us to group data into more meaningful structures. This lesson focuses on defining and instantiating structs and enums, the two primary ways to create custom data types in Rust. For you, coming from C++, structs will feel familiar, but you'll discover that Rust's enums are significantly more powerful than their C counterparts.
Structs: Grouping Related Data
A struct, short for structure, is a custom data type that lets you package together and name multiple related values that make up a meaningful group. It's conceptually similar to a struct in C/C++ or a class with only public data members.
To see why structs are so useful, let's consider a practical example. Imagine you're writing a program to calculate the area of a rectangle. You could pass the width and height as separate arguments, or perhaps as a tuple. However, a struct makes the relationship between the data explicit and your code more readable.
The video "Structs in Rust" provides an excellent demonstration of refactoring a simple program to use structs, highlighting their practical value.
Watch the segment from this practical example. Observe how the code evolves from using separate variables, to a tuple, and finally to a much cleaner struct. Pay attention to how the struct clarifies the intent of the code.
As the video demonstrates, using a struct makes our code more robust and self-documenting.
Defining and Instantiating Structs
Now that you've seen the 'why', let's look at the 'how'. The official Rust book provides a clear and concise guide to the syntax.
Defining and Instantiating Structs - The Rust Programming ...
This chapter from "The Rust Programming Language" covers the fundamentals of defining and using structs.
Read the initial section, from the beginning down to just before the "Field Init Shorthand" subsection. Focus on the syntax for defining a struct, creating an instance, and accessing or modifying its fields with dot notation.
Here's the User struct from the reading, which we'll use in our examples:
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}
fn main() {
let mut user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
// Accessing a field
user1.email = String::from("anotheremail@example.com");
println!("The user's email is: {}", user1.email);
}
Notice that to modify user1, the entire instance must be marked as mut. Rust doesn't allow marking individual fields as mutable.
Syntactic Sugar for Structs
Rust provides a couple of convenient shortcuts for working with structs, which help to reduce boilerplate code.
Defining and Instantiating Structs - The Rust Programming ...
Let's continue with the same Rust book chapter to learn about these handy features.
Read the two short subsections on field init shorthand and struct update syntax.
-
Field Init Shorthand: If a function parameter has the same name as a struct field, you can use a shorthand when creating an instance.
fn build_user(email: String, username: String) -> User { User { email, // Shorthand for email: email, username, // Shorthand for username: username, active: true, sign_in_count: 1, } } -
Struct Update Syntax: You can create a new instance using some values from an old instance with the
..syntax.let user2 = User { email: String::from("another@example.com"), ..user1 // The rest of the fields come from user1 };
It is crucial to understand how this update syntax interacts with the ownership rules we learned. If a field's type implements the Copy trait (like u64 or bool), its value is copied. If the field's type does not implement Copy (like String), its value is moved. In the example above, user1.username is moved to user2, so user1 as a whole can no longer be used. This prevents having two owners for the same String data.
Tuple and Unit-Like Structs
Rust also supports two other, simpler kinds of structs.
Defining and Instantiating Structs - The Rust Programming ...
Finally, let's look at two other struct variants.
Quickly read the sections on tuple structs and unit-like structs.
-
Tuple Structs: These are named tuples. They are useful when you want to give a tuple a distinct name and type, but the fields don't need explicit names. For example,
struct Color(u8, u8, u8);andstruct Point(i32, i32, i32);define two different types, even though their internal data structure is similar. -
Unit-Like Structs: These have no fields at all. They are useful in generic programming when you need to represent a type that has behavior (
impl) but no data. For example:struct AlwaysEqual;.
Enums: A Value from a Set of Possibilities
While a struct allows you to say "a User has a username and an email and an active status," an enum (enumeration) allows you to say "a value is one of these possible things." This is where Rust's enums far exceed the capabilities of enums in C/C++, which are often just aliases for integer constants.
In Rust, an enum variant can have data associated with it, and each variant can have different types and amounts of data. This makes enums an incredibly flexible tool for modeling a type that can be in one of several different states.
Let's start with the basics from the Rust book.
Defining an Enum - The Rust Programming Language
This chapter introduces enums and their powerful ability to embed data.
First, read the introduction to understand the core concept of an enum. Next, read through the sections explaining how to create enum values and, most importantly, how to attach data to enum variants. The IpAddr and Message examples are key here.
Let's look at the Message enum from the reading, which is a perfect illustration of this power:
enum Message {
Quit, // No data associated
Move { x: i32, y: i32 }, // Anonymous struct-like data
Write(String), // A single String
ChangeColor(u8, u8, u8), // A tuple of three values
}
fn main() {
let msg1 = Message::Move { x: 10, y: 20 };
let msg2 = Message::Write(String::from("hello"));
}
Here, Message is a single type, but a variable of type Message can represent four completely different states, each with its own associated data. This allows you to pass any of these variants to a function that accepts a Message, which is something you couldn't easily do if they were all separate structs.
Enums Under the Hood
Given your background in C/C++ and interest in embedded systems, you might be wondering how this is represented in memory. The compiler performs a clever optimization. It allocates enough space to hold the largest variant, and adds a small piece of data called a discriminant (or tag) to keep track of which variant is currently stored.

This is analogous to a "tagged union" pattern in C, but in Rust, it's completely memory-safe. The compiler will never let you access the data for a Move variant if the enum currently holds a Quit variant.
A Very Special Enum: Option
Rust uses its powerful enum system to solve a problem that plagues many other languages, including C++ and Python: the concept of null. Null values (or None in Python, nullptr in modern C++) are a common source of bugs, arising when developers forget to check if a value is null before trying to use it.
Rust's solution is the Option<T> enum, which is defined in the standard library.
Defining an Enum - The Rust Programming Language
The Option enum is a brilliant case study in how Rust uses its type system to prevent common bugs.
Read the section on The Option Enum. Pay close attention to why Option<T> is better than a null value.
The Option<T> enum is defined as:
enum Option<T> {
None,
Some(T),
}
It expresses that a value can either be something (Some(value)) or nothing (None). Because Option<i32> and i32 are different types, the Rust compiler will not let you use an Option<i32> as if it were a regular i32 (for example, by trying to add it to another number). You are forced by the compiler to handle the None case, which eliminates null-reference-style runtime errors.
Conclusion
In this lesson, we've unlocked the ability to create our own data types in Rust. You now have the primary tools for modeling the data in your applications.
Here are the key takeaways:
- Structs are for grouping related data together. You use a struct when your type has several properties that exist simultaneously (an
andrelationship). - Enums are for defining a type that can be one of several possible variants. You use an enum when your type can be one of a few different things (an
orrelationship). - Rust's
enumsare exceptionally powerful because each variant can hold different types and amounts of data, making them far more flexible than C-style enums. - The
Option<T>enum is a core part of Rust that provides null safety by forcing the compiler to check for the absence of a value.
Now that we can create enums with different variants, a new question arises: how do we write code that does different things depending on which enum variant we have? In our next lesson, we will explore Rust's powerful pattern matching constructs, match and if let, which are designed precisely for this purpose.