Defining a struct
What you'll learn:
- declare your own struct, fill in its fields and read them with a dot;
- add methods to a struct and choose between
&self,&mut selfandself; - write functions like
newand call them with::; - print a whole struct with
{:?}using#[derive(Debug)].

Picture a paper form. It has the fields "Name", "City" and "Age", and each field has its own label. Everything a person wrote about themselves sits on one sheet, and you can hand that sheet over in one piece.
Without a form, the facts about a person scatter into separate variables name, city and age, and a function that needs a person takes three parameters. The tuple ("Anna", "Riga", 30) keeps them together, but it does not remember which is the name and which is the city: person.1 tells the reader nothing. In Rust you gather related values into a type of your own:
struct User {
name: String,
city: String,
age: u32,
}
fn main() {
let anna = User {
name: String::from("Anna"),
city: String::from("Riga"),
age: 30,
};
println!("{} {} {}", anna.name, anna.city, anna.age); // Anna Riga 30
}Let's walk through the example line by line:
struct User { … }describes a blank form: three fields and the type of each.let anna = User { … };fills in such a form: it writesAnnaintoname,Rigaintocityand30intoage.anna.name,anna.cityandanna.ageread the fields by name.println!printsAnna Riga 30.
Declaration and literal
A struct is a type you declare yourself: it gathers several values under one name. Each of those values is a field with its own name and type. The declaration has these parts:
structis the keyword: "I am declaring a struct";Useris the type's name, capitalized inCamelCasestyle;- the fields go inside the braces, one per line: name, colon, type and a comma.
The declaration creates nothing by itself; it only describes the blank form. A struct literal creates a value: the type's name, then each field with its value inside braces. You reach a field with a dot: anna.age reads the age field of the form anna.
The fields in a literal can come in any order, but you cannot leave one out. Without age the compiler answers error[E0063]: missing field `age` in initializer of `User` .
This is where the form analogy falls short. On paper you can leave a field blank or add a new one in the margin. A struct's set of fields is fixed once by its declaration, and a literal must fill in every one of them.
mut belongs to the whole variable
A struct follows the same rules as any variable: without mut you cannot change it. You write mut on the variable, and then you can change any of its fields:
let mut anna = User {
age: 30,
name: String::from("Anna"),
city: String::from("Riga"),
};
anna.age += 1;
anna.city = String::from("Oslo");
println!("{} {} {}", anna.name, anna.city, anna.age); // Anna Oslo 31Let's go step by step:
let mut annaallows the form to change. The fields in the literal come in a different order than in the declaration, and that is not an error.anna.age += 1adds one to theagefield.anna.city = String::from("Oslo")puts a new string into the field. The old stringRigais destroyed right away, without waiting for}: the assignment takes it from its only owner, the field.println!printsAnna Oslo 31.
You cannot mark a single field as mutable: Rust has no mut for one field. Interviewers like to ask this: "Can you make only the age field mutable?" The answer is no. Mutability is set for the whole variable, and with let mut any field can change.
Shorter literals
There are two ways to shorten a literal.
A field from a variable of the same name
If the value sits in a variable with the same name as the field, you write name instead of name: name. The string moves from the variable into the field, as with an ordinary let.
Struct update syntax
Struct update syntax is the ..anna at the end of a literal. It means "take the remaining fields from anna". Let's walk through both shortcuts in one example:
let name = String::from("Anna");
let anna = User {
name,
city: String::from("Riga"),
age: 30,
};
let boris = User {
name: String::from("Boris"),
..anna
};
println!("{} {} {}", boris.name, boris.city, boris.age); // Boris Riga 30
println!("{} {}", anna.name, anna.age); // Anna 30let name = …puts the stringAnnainto the variablename.- In the literal for
anna,name,meansname: name: the string goes into the field. - The literal for
borissetsnameitself, and..annafills in the fields the literal leaves out:cityandage. - The first print shows
Boris Riga 30: his own name, the city and age fromanna. - The second print shows
Anna 30: these fields ofannastayed in place.
A field written in the literal always wins over ..anna, and nothing overwrites it. The word "update" is misleading, though: ..anna carries fields over by the ordinary ownership rules. The number age is a Copy type, so it is copied. The string city moves into boris, and printing anna.city no longer compiles: error[E0382]: borrow of moved value: `anna.city` .
..anna always comes last, with no comma after it.
Common mistake
A field is changed on a variable declared without mut:
let anna = User {
name: String::from("Anna"),
city: String::from("Riga"),
age: 30,
};
anna.age += 1; // ✗
println!("{} {} {}", anna.name, anna.city, anna.age);error[E0594]: cannot assign to `anna.age`, as `anna` is not declared as mutableThe program does not compile: anna is declared without mut, so all its fields are read-only. This is a build error, not a panic. Below the error the compiler suggests the fix: let mut anna.
Key points
- A struct gathers named fields into one type; a literal fills in every field, and you read a field with a dot.
mutbelongs only to the whole variable: withoutlet mutno field can change (E0594).nameinstead ofname: nameis the short form for a field from a variable of the same name...annatakes fromannathe fields the literal leaves out, and moves the ones that are notCopy.