Chapter 9: Structs in Rust
Structs are a cornerstone of Rust’s type system, allowing you to create custom data types by grouping related data fields into a single, named entity. This concept is directly comparable to C’s struct
. Like C structs, Rust structs aggregate fields where each field can have a different type, and instances typically have a fixed size known at compile time.
However, Rust enhances the concept significantly. Rust structs enforce memory safety through the ownership system and allow associated functions and methods to be defined, providing behavior encapsulation similar to classes in object-oriented languages like C++ or Java, but without inheritance.
In this chapter, we will cover:
- Defining struct types (including named-field, tuple, and unit structs) and creating instances
- Understanding struct fields and accessing/modifying them
- Basic operations like assignment and comparison (via traits)
- Destructuring structs and moving fields out
- Field initialization shorthand and the struct update syntax
- Using default values with the
Default
trait - Defining behavior with methods and associated functions (
impl
blocks) - Understanding the
self
,&self
, and&mut self
parameters - Implementing getters and setters for controlled access
- Ownership rules concerning structs and their fields
- Using references and lifetimes within structs
- Creating generic structs for type flexibility
- Deriving common traits like
Debug
(for printing),Clone
, andPartialEq
(for comparison) - Struct memory layout considerations (
#[repr(C)]
) - Visibility (
pub
) and modules overview - Exercises for practice