Sub topic 1
Defining a struct
A struct is Rust's way of grouping related values into one type with named parts. This chapter covers the definition itself: the syntax, the rules the compiler enforces, how a struct is laid out in memory, and the mistakes that most often trip people up. Creating instances, methods, and traits get their own chapters, so the examples here only build values as far as needed to show a definition working.
Prerequisites
This chapter assumes you already know the following:
- Basic Rust syntax: variables, functions, and primitive types such as
u32,bool, andf64. - Ownership and borrowing basics: what a move is, and the difference between
&and&mut. - How to build and run a program with
cargo run.
What a struct is
A struct is a user-defined type made of a fixed set of fields. Each field has a name and a type. Compared with a tuple, the names make the code self-describing: user.email is clearer than user.1. Compared with a class in other languages, a struct holds data only. Behavior is attached separately with impl blocks, which a later chapter covers.
A struct definition creates a new type. Two structs with identical fields are still different types, and the compiler will not let you pass one where the other is expected.
The syntax
You define a named-field struct with the struct keyword, a name, and a braced list of field: Type pairs separated by commas.
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
fn main() {
let user = User {
username: String::from("ada"),
email: String::from("[email protected]"),
sign_in_count: 1,
active: true,
};
println!(
"{} <{}> signed in {} time(s), active: {}",
user.username, user.email, user.sign_in_count, user.active
);
}The rules that apply to every definition:
- Type names use
UpperCamelCaseand field names usesnake_case. The compiler warns when you break this convention. - Every field needs an explicit type. Rust does not infer field types from usage.
- Fields cannot have default values in the definition. Defaults come from the
Defaulttrait or from a constructor function, both covered later. - A trailing comma after the last field is allowed and is the usual style, because it keeps diffs small when you add a field.
- Field order in the definition does not matter when you create an instance, but it does affect
deriveoutput such as the order shown byDebug. - The order of items in a file does not matter. You can use a struct above the line where it is defined.
Where a struct can be defined
Most structs live at module level, next to the functions that use them. You can also define a struct inside a function body. It is then visible only within that function, which is useful for a throwaway helper type.
Visibility is separate for the struct and for each field. Writing pub struct User makes the type public, but its fields stay private unless you also write pub on each one. The privacy chapter covers this in detail. For now, remember that a field's visibility is decided where you define it.
How the fields sit in memory
A struct stores its fields together in one block, with no pointer or header added by the language. A User holds its two String values (each a pointer, capacity, and length), a u64, and a bool directly inside it. The text data of the strings lives on the heap, but the String handles are inside the struct.
Because of alignment, the compiler may insert padding between fields. By default Rust is also free to reorder fields to reduce that padding. This differs from C, where declaration order fixes the layout.
use std::mem::size_of;
#[allow(dead_code)]
struct Mixed {
a: u8,
b: u32,
c: u8,
}
#[allow(dead_code)]
struct Sorted {
b: u32,
a: u8,
c: u8,
}
fn main() {
println!("Mixed: {} bytes", size_of::<Mixed>());
println!("Sorted: {} bytes", size_of::<Sorted>());
}With current compilers both lines print 8, because the compiler reorders Mixed to match Sorted. The language does not guarantee this. If you need a fixed layout, for example when talking to C code, add #[repr(C)] above the struct. In that case Mixed would take 12 bytes.
Field types and ownership
Struct fields normally own their data. A String field means the struct owns that text, and when the struct is dropped, the text is freed with it. This is the simplest design and the one to start with.
A field can instead hold a reference such as &str, but then the definition must name a lifetime, and the struct cannot outlive the data it borrows. The chapter on structs that borrow data covers this. If you write name: &str without a lifetime, the compiler reports error E0106 (missing lifetime specifier).
A struct cannot contain itself
The compiler must know the exact size of every struct. A struct that directly contains itself would have infinite size, so this is rejected:
struct Node {
value: i32,
next: Option<Node>,
}The fix is to put the recursive part behind a pointer with a known size. Box<T> is a heap pointer, so Option<Box<Node>> has a fixed size no matter how long the chain is:
#[derive(Debug)]
struct Node {
value: i32,
next: Option<Box<Node>>,
}
fn main() {
let tail = Node { value: 2, next: None };
let head = Node { value: 1, next: Some(Box::new(tail)) };
println!("{:?}", head);
}This prints Node { value: 1, next: Some(Node { value: 2, next: None }) }. The #[derive(Debug)] line is what makes {:?} work. Without it, printing a struct with {:?} fails to compile. The derive chapter explains it fully.
Definition versus instance
The definition is a blueprint that exists only at compile time. Instances are the values created from it at run time. One definition can produce any number of independent instances.
Other shapes of definition
Named-field structs are the most common form, but two other forms exist. A tuple struct has unnamed fields in parentheses, such as struct Meters(f64);. A unit struct has no fields at all, such as struct Marker;. A later chapter covers both. One edge case is worth knowing now: struct Empty {} and struct Empty; both define a type with no fields, but they are not interchangeable at the use site. A unit struct is created by writing just its name, while the braced form needs Empty {}.
Common errors
| Mistake | What the compiler says | Fix |
|---|---|---|
| Writing `username = String::new()` instead of `username: String::new()` | Expected `:` in a field initializer | Use `:` between field name and value |
| Leaving out a field when creating an instance | E0063, missing field | Supply every field, or use struct update syntax |
| Giving a field a default in the definition, such as `active: bool = true` | Unexpected `=` in a field declaration | Use a constructor or `Default` |
| Using a `&str` field without a lifetime | E0106, missing lifetime specifier | Own a `String`, or add a lifetime parameter |
| Printing with `{:?}` and no `Debug` | `Debug` is not implemented | Add `#[derive(Debug)]` |
| A struct that contains itself | E0072, recursive type has infinite size | Wrap the inner value in `Box` |
Summary of the design choices
When you define a struct, you are deciding what the type owns, what it exposes, and what it can do. Start with owned fields, private visibility, and the smallest set of derives you need. Loosen these choices only when a real need appears.
Exercise
Define a struct named Book with a title (owned text), a pages count (a non-negative whole number), and an available flag. Then create one Book in main and print its title. Why is String a better choice than &str for title at this stage?
Show answer
struct Book { title: String, pages: u32, available: bool } and in main: let b = Book { title: String::from("Dune"), pages: 612, available: true }; println!("{}", b.title);. String is better because the struct then owns its text. A &str field would need an explicit lifetime parameter and would restrict the struct to live no longer than the text it borrows.
Exercise
This definition does not compile. Explain why, and show a fix. struct Tree { value: i32, left: Option<Tree>, right: Option<Tree>, }
Show answer
Tree contains two Option<Tree> values, so its size would depend on itself and be infinite (error E0072). Wrap the children in Box so each field is a fixed-size pointer: left: Option<Box<Tree>>, right: Option<Box<Tree>>.