Sub topic 1
Defining a Struct
A struct groups related values under one name. Each value is a field with its own name and type. This chapter covers the definition syntax and the three struct forms. Creating instances, methods, and the other topics in the plan come in later chapters.
Prerequisites
This chapter assumes you know:
- Basic Rust syntax: variables, functions, and primitive types.
- Ownership and borrowing basics: move,
&, and&mut. - How to build and run a program with
cargo.
Why structs
A function that takes width: u32, height: u32 has two loose numbers. Nothing in the types says they belong together, and callers can swap them by mistake. A struct bundles them into one type with a name, so the compiler can check how you use them.
Named-field structs
Use the struct keyword, a name in CamelCase, and a list of fields in braces. Each field is written as name: Type, and fields are separated by commas.
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let r = Rectangle { width: 3, height: 4 };
println!("{} x {}", r.width, r.height);
}The definition describes a type and allocates nothing. Memory is used only when you create a value, which the next chapter covers. The main function above gives a first look. It builds a value with Rectangle { ... } and reads a field with a dot.
Every field needs a concrete type. A struct that owns its data usually uses owned types such as String rather than &str. Fields that borrow need lifetime annotations, which a later chapter covers.
Tuple structs and unit structs
Rust has two other forms.
A tuple struct has a name but its fields have no names. You reach them by position.
struct Meters(f64);
fn main() {
let distance = Meters(12.5);
println!("{} m", distance.0);
}A unit struct has no fields at all.
struct Marker;
fn main() {
let _marker = Marker;
}The three forms compare as follows.
| Form | Definition | Fields reached by | Typical use |
|---|---|---|---|
| Named-field | `struct P { x: i32 }` | Name (`p.x`) | Most data types |
| Tuple | `struct P(i32);` | Position (`p.0`) | Wrapping one or two values, giving a distinct type |
| Unit | `struct P;` | Not applicable | Marker types that carry no data |
Two tuple structs with identical field types are still different types. Meters(1.0) cannot be passed where a Feet(f64) is expected. This is the basis of the newtype pattern in a later chapter.
Where definitions go
Define structs at the top level of a module, outside any function. Definitions can appear in any order within a file, so main may use a struct declared below it. You can declare a struct inside a function body, but then it is visible only in that function.
Common errors
- Forgetting the comma between fields gives a syntax error.
- Writing
struct Marker();orstruct Marker {}is legal, butstruct Marker;is the usual form for a unit struct. - Using a bare reference such as
&stras a field type gives the error "missing lifetime specifier". UseString, or add a lifetime.
Exercise
Define a tuple struct named Celsius that wraps an f64. Why can't you pass a Celsius to a function that expects a bare f64?
Show answer
struct Celsius(f64); defines it. A tuple struct is a distinct type from the type it wraps, so the compiler rejects Celsius where f64 is expected. You must read the inner value with .0.