Structs
A struct is your own data type that gathers several named values, called fields, into one whole: a user with a name and an age, a rectangle with a width and a height. You declare it with the struct keyword and create an instance with a literal that lists all the fields. Unlike classes in Java or C++, a struct has no inheritance and no constructors: struct describes the data, and behaviour is added separately, in an impl block.
Structs are the first place where ownership meets your own types. Mutability is set for the whole variable, not for a single field. The struct update syntax ..other does not copy but moves the fields that have no Copy. The way a method takes self decides what it can do with the value: read it (&self), change it (&mut self) or take it for itself (self). Functions in an impl without self are called associated functions, you call them with :: — Rectangle::new(3, 4) — and the best known of them, new, is just a naming convention, not a keyword. Finally, the #[derive] attribute gives a struct printing with {:?}, copying, comparison and hashing in one line — as long as every field can do all that. This topic walks through structs layer by layer — from the declaration to derive.
Topic map
- Struct Basics — a
structwith named fields, a literal with all the fields and access with a dot;mutonly exists on the whole variable (E0594); field init shorthand;..othermoves the fields withoutCopy; a field usually owns its data — aString, not a&str. - Tuple and Unit Structs — fields without names and access through
.0; the newtypestruct UserId(u64)gives type checking at no cost;typeonly creates an alias; the unit structstruct Marker;takes 0 bytes. - Methods — functions in an
implblock whose first parameter isself;&selfreads,&mut selfchanges,selftakes the value;E0596on a variable withoutmut; on a dot call the compiler adds&and&mutitself. - Associated Functions — functions in an
implwithoutself, called with::;Selfis the name of the current type;newis a convention, not a keyword; instead of overloading — constructors with different names; a type can have severalimplblocks. - Deriving Traits —
#[derive]generatesDebug,Clone,Copy,PartialEq,Eq,Hash,Default,PartialOrdandOrdif every field implements them;{:?}and{:#?};Displayis written by hand; the warning about a field nobody reads.
Common mistakes and traps
| Mistake | Consequence |
|---|---|
Changing a field of a variable without mut, hoping for a "mutable field" | error[E0594]: cannot assign to `user.age`, as `user` is not declared as mutable: mut only exists on the whole variable |
Using the original struct after ..other | The fields without Copy have moved, and a reference to the whole struct gives error[E0382]: borrow of partially moved value: `anna` |
Calling a &mut self method on a variable without mut | error[E0596]: cannot borrow `rect` as mutable, as it is not declared as mutable |
Calling an associated function with a dot: a.square(5) | error[E0599]: no method named `square` found for struct `Rectangle` in the current scope; the right form is Rectangle::square(5) |
Declaring a field as &str instead of String | error[E0106]: missing lifetime specifier: a reference in a field needs a lifetime, and the struct cannot outlive the data it points to |
Putting #[derive(Clone, Copy)] on a struct with a String | error[E0204]: the trait `Copy` cannot be implemented for this type |
Writing #[derive(Display)] | error: cannot find derive macro `Display` in this scope: Display is implemented by hand |
Why it matters in interviews
Structs are the topic where a junior interview checks ownership no longer on String and i32 but on your own types. The syntax here is simple, so the questions are about the consequences: what happens to the original value after ..other or after calling a method that takes self, and why the compiler refused to change a field.
What interviewers usually check:
- How named, tuple and unit structs differ and when each fits; what a newtype is and why it beats a
typealias. - What
self,&self,&mut selfandSelfmean in animplblock and what each kind ofselflets a method do. - How a method differs from an associated function and why
newis a convention, not a constructor. - Why mutability is set for the whole variable and what
..otherdoes to the fields of the original struct. - Why a field usually holds a
Stringrather than a&str. - What
#[derive]generates, what each trait requires of the fields, whetherPartialEqbringsEqalong, and whyDisplayis implemented by hand.