Skip to content
Theory · Structs · lesson 1 of 8

Defining a struct

What you'll learn

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 self and self;
  • write functions like new and call them with ::;
  • print a whole struct with {:?} using #[derive(Debug)].
A blank form User and a filled form anna, and over its third box hangs a magnifier tagged anna.age

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:

Rust
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:

  1. struct User { … } describes a blank form: three fields and the type of each.
  2. let anna = User { … }; fills in such a form: it writes Anna into name, Riga into city and 30 into age.
  3. anna.name, anna.city and anna.age read the fields by name.
  4. println! prints Anna 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:

  • struct is the keyword: "I am declaring a struct";
  • User is the type's name, capitalized in CamelCase style;
  • 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:

Rust
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 31

Let's go step by step:

  1. let mut anna allows the form to change. The fields in the literal come in a different order than in the declaration, and that is not an error.
  2. anna.age += 1 adds one to the age field.
  3. anna.city = String::from("Oslo") puts a new string into the field. The old string Riga is destroyed right away, without waiting for }: the assignment takes it from its only owner, the field.
  4. println! prints Anna 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:

Rust
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 30
  1. let name = … puts the string Anna into the variable name.
  2. In the literal for anna, name, means name: name: the string goes into the field.
  3. The literal for boris sets name itself, and ..anna fills in the fields the literal leaves out: city and age.
  4. The first print shows Boris Riga 30: his own name, the city and age from anna.
  5. The second print shows Anna 30: these fields of anna stayed 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:

Rust
let anna = User {
    name: String::from("Anna"),
    city: String::from("Riga"),
    age: 30,
};
anna.age += 1; // ✗
println!("{} {} {}", anna.name, anna.city, anna.age);
TEXT
error[E0594]: cannot assign to `anna.age`, as `anna` is not declared as mutable

The 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.
  • mut belongs only to the whole variable: without let mut no field can change (E0594).
  • name instead of name: name is the short form for a field from a variable of the same name.
  • ..anna takes from anna the fields the literal leaves out, and moves the ones that are not Copy.