Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 132 ยท Structs, Enums and Traits Basics

Structs

Learn Rust structs - named-field, tuple and unit structs, field init shorthand, struct update syntax, ownership of fields, derive Debug, memory layout and builders.

So far your programs have worked with single values: numbers, strings, tuples, vectors. Real programs deal with things: a user, a point on a map, a configuration, a bank account. Each of those is several values that belong together and deserve a name. In Rust you build such types with a struct (short for "structure"). A struct bundles related values into one type with named parts, and the compiler then checks that you never mix up a UserId with a Meters.

This lesson covers the three kinds of struct, how to create and update them, how ownership works for their fields, how to print them with #[derive(Debug)], what they look like in memory, and a first look at builder-style construction. In the next lesson, Methods and Associated Functions, you will give structs behavior.

Named-field structs

The most common kind lists each field with a name and a type:

Rust Defining and using a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

A struct definition is an item: it lives outside functions and describes a type. A struct value is created with the same name followed by braces and a value for every field. You may write the fields in any order, but you cannot leave one out; Rust has no "default null" for a missing field. You read a field with a dot: book.title.

By convention struct names are PascalCase and fields are snake_case, and the last field gets a trailing comma so that adding a field later changes only one line.

Fields are immutable unless the whole value is mut

Mutability belongs to the binding, not to individual fields. If you want to change a field, declare the variable with mut; then every field becomes changeable:

Rust Mutating a field

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

There is no way to mark just one field as mut. If part of a type must never change, hide it behind a method and keep the field private (you will see how in Modules).

Field init shorthand

When a variable has the same name as the field it fills, you can write the name once. This is idiomatic in constructor-like functions:

Rust Field init shorthand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The function body is a single expression, a Point { ... } literal, with no semicolon, so it is the return value (see Rust Syntax).

Struct update syntax

Often you want a new value that is mostly a copy of an existing one with a few changes. The .. syntax fills in all remaining fields from another instance:

Rust Struct update syntax with ..

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The ..expr part must come last and has no trailing comma. Pay attention to a subtle point: the fields that are copied move out of the source, exactly like any other assignment (see Ownership). If you used ..defaults instead of ..defaults.clone(), the String field name is explicitly set, so it would not be moved, but any remaining String field would be. Here only Copy fields (volume, muted) come from defaults, so even ..defaults would leave defaults usable. When in doubt, clone the source, or let the compiler tell you.

Printing a struct with derive(Debug)

Try to print a struct with {:?} and the compiler stops you, because your type has no idea how to print itself:

Rust Printing without Debug (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler reports:

TEXT
error[E0277]: `Point` doesn't implement `Debug`
 --> main.rs:8:22
  |
8 |     println!("{:?}", p);
  |               ----   ^ `Point` cannot be formatted using `{:?}` because it doesn't implement `Debug`
  |               |
  |               required by this formatting parameter
  |
  = help: the trait `Debug` is not implemented for `Point`
help: consider annotating `Point` with `#[derive(Debug)]`

The fix is in the help line: add #[derive(Debug)] above the struct. A derive asks the compiler to write a standard trait implementation for you (more in Traits). With it, {:?} prints on one line and {:#?} prints a readable multi-line "pretty" version:

Rust derive(Debug) and pretty printing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Use Debug output for developers and logs. For text meant for end users you implement Display yourself, which Display, From and Standard Conversion Traits covers.

Ownership of fields

A struct owns its fields. When the struct is dropped, all its fields are dropped too. When you move a field out of a struct, the struct becomes partially moved, and you can still use the other fields:

Rust Partial moves out of a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

But you can no longer use profile as a whole (for example pass it to a function), because part of it is gone.

Structs holding references need lifetimes

What if a field should borrow instead of own? For example title: &str. Rust then needs to know how long the borrowed data lives:

Rust A reference field without a lifetime (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler reports:

TEXT
error[E0106]: missing lifetime specifier
 --> main.rs:2:11
  |
2 |     text: &str,
  |           ^ expected named lifetime parameter
  |
help: consider introducing a named lifetime parameter
  |
1 ~ struct Label<'a> {
2 ~     text: &'a str,

The easy fix for a beginner is to own the data: use String instead of &str. Borrowing fields are covered in Lifetimes, and they are worth it only when you know why you need them. A good default is: structs own their data.

Tuple structs

Sometimes the fields do not need names. A tuple struct gives a tuple a distinct type name:

Rust Tuple structs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Fields are accessed by position (.0, .1) or destructured with a pattern. The big win is that Meters and Seconds are different types even though both wrap an f64, so speed(t, d) is a compile error. A tuple struct with one field is called a newtype, and it is the cheapest way to make mistakes impossible. It costs nothing at runtime: Meters has exactly the size of an f64.

Unit structs

A struct with no fields at all is a unit struct. It occupies zero bytes and is useful as a marker or as a type that carries behavior but no data (you will meet it again in Traits):

Rust Unit structs are zero-sized

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Why a unit struct is free, and the aliasing rule

Tuple structs and unit structs also show up in the rules that make Rust safe. The core rule is aliasing XOR mutability: at any moment a value may have many shared references (&T) or exactly one exclusive reference (&mut T), never both. Struct fields follow the same rule field by field, and the compiler can see that two different fields of one struct are independent:

Rust Borrowing two fields at once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Borrowing the whole struct through a method that takes &mut self would lock all fields for the call, and the example above would fail if name were still in use. When that hurts, borrow the fields directly or split the struct into smaller ones. A unit struct has no fields, so it can never be involved in an aliasing conflict: copying a Marker around costs nothing and borrowing it is harmless.

Struct layout in memory

A struct's fields sit next to each other in memory, usually on the stack. Pair above holds a u8 and a u32, which need 1 and 4 bytes. The result is 8, not 5, because the u32 must start at an address divisible by 4, so there is padding. Unlike C, Rust is allowed to reorder fields to waste less padding, and does not promise any particular order unless you ask with #[repr(C)]. You never need to think about this to write correct programs; it matters when you care about size and speed (Memory Layout and Sizes goes deeper).

Builder-style construction

Structs with many fields and sensible defaults are awkward to create. One idiom is a chain of methods that each take self by value, change one thing and return it. You have not seen methods yet (next lesson), so here is a preview that reads almost like English:

Rust A small builder preview

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The full pattern, with a separate builder type, appears in Type-State and Builder Patterns.

When to use which struct

  • Named fields for anything with more than one or two parts, or when the meaning of each part is not obvious from its position.
  • Tuple struct for newtypes (one field) and for tiny things like Rgb(r, g, b).
  • Unit struct for markers and for types that exist only to implement traits.
  • Prefer owned fields (String, Vec<T>) first; add references and lifetimes only when you have a measured reason.

Derive Debug on almost every struct you write. It costs nothing at runtime when unused and makes dbg! and error messages far more useful.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about creating a struct value is true?

    Rust has no implicit defaults. Every field needs a value, though the order does not matter. Struct update syntax (..other) can supply the rest from another value.
  2. 2. How do you make one field of a struct changeable?

    Mutability belongs to the binding. With let mut, every field of that value can be assigned. There is no per-field mut.
  3. 3. What is the main benefit of a newtype such as struct Meters(f64)?

    A newtype has the same size and speed as the wrapped value but is a different type, so the compiler rejects mixing units by mistake.
  4. 4. What does the compiler tell you for struct Label { text: &str }?

    A reference stored in a struct needs a named lifetime. The beginner-friendly fix is to own the data with String.
  5. 5. After let name = profile.name; (a String field), which statement is true?

    Moving one field leaves the struct partially moved. The other fields stay usable, but the struct as a whole cannot be passed around.

Summary

  • A struct groups named values into a new type; create one by giving every field a value.
  • Mutability is per binding, not per field; use let mut to change fields.
  • Field init shorthand (Point { x, y }) and update syntax (..other) reduce boilerplate; update syntax moves non-Copy fields.
  • #[derive(Debug)] enables {:?} and {:#?}.
  • Structs own their fields; moving a field out leaves a partially moved struct. Reference fields need lifetimes.
  • Tuple structs (newtypes) and unit structs complement named-field structs.
  • Rust may reorder fields and add padding; size_of shows the real size.

Next: Methods and Associated Functions