Skip to main content

How to Define and Use a Struct in Rust

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

A struct groups related values under one name, each with its own field name and type. A Book can hold a title and a year together, and the code reads them as book.title and book.year.

Syntax​

Syntax
struct <Name> {
<field>: <Type>,
<field>: <Type>,
}

let <variable> = <Name> {
<field>: <value>,
<field>: <value>,
};

<variable>.<field>
PartWhat it does
struct <Name>Defines a new type named <Name>.
<field>: <Type>One named piece of data and its type, such as year: u32.
<Name> { <field>: <value>, … }Creates a value of the struct, called an instance, with every field set.
<variable>.<field>Reads one field of the instance.

The Rust Book's chapter on structs compares them with tuples: "Unlike with tuples, in a struct you’ll name each piece of data so it’s clear what the values mean."

The Example​

The example defines a Book with a title and a year, creates the book Dune, and prints both fields.

Prerequisites​

  • Rust, installed with rustup, which comes with Cargo. This guide uses Rust 1.100.0.

Step 1: Create a Project​

Terminal
cargo new demo
cd demo
Output
Creating binary (application) `demo` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

cargo new demo creates a folder named demo with a Cargo.toml file, which describes the project, and src/main.rs, which holds the code. cd demo moves into it.

Step 2: Write the Code​

Replace the contents of src/main.rs with:

src/main.rs, which defines a struct Book with a String title and a u32 year, creates Dune from 1965, and prints both fields.

src/main.rs
struct Book {
title: String,
year: u32,
}

fn main() {
let book = Book {
title: String::from("Dune"),
year: 1965,
};
println!("{} ({})", book.title, book.year);
}

title: String holds text the struct owns, and year: u32 holds an unsigned 32-bit number. String::from("Dune") turns the text into a String. book.title and book.year read the two fields, and println! puts them into its two {} places in order.

Step 3: Run It​

Terminal
cargo run -q
Output
Dune (1965)

A zsh terminal where cargo run -q prints Dune (1965).

cargo run compiles the program and runs it, and -q hides Cargo's own status lines, so only the program's output is left.

Change a Field​

To change a field after creating the instance, declare the variable with let mut. Without mut, book.year = 1966; stops the build:

Output
error[E0594]: cannot assign to `book.year`, as `book` is not declared as mutable

With mut, the change works. When a variable already has a field's name, you can also write the field once instead of title: title, which the Book calls field init shorthand:

src/main.rs
fn main() {
let title = String::from("Dune");
let mut book = Book { title, year: 1965 };
book.year = 1966;
println!("{} ({})", book.title, book.year);
}
Output
Dune (1966)

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out a fielderror[E0063]: missing field `year` in initializer of `Book` Set every field
Printing the whole struct with {}error[E0277]: `Book` doesn't implement `std::fmt::Display` Print its fields, or derive Debug and print with {:?}
Changing a field of a variable declared without muterror[E0594]: cannot assign to `book.year`, as `book` is not declared as mutableDeclare it with let mut

Troubleshooting​

SymptomLikely causeFix
missing field `…` in initializerA field has no valueAdd the field to the struct literal
doesn't implement `std::fmt::Display` {} doesn't know how to print the structPrint a field, or use {:?} with #[derive(Debug)]
as `…` is not declared as mutableThe variable is immutableUse let mut

FAQ​

Do I need mut to read a field?​

No. The example reads book.title and book.year from a variable declared with plain let. Only changing a field needs mut.

Does the order of fields in the literal matter?​

No. Fields are matched by name, so Book { year: 1965, title: String::from("Dune") } creates the same book.

Conclusion​

struct defines a type with named fields, a struct literal creates an instance with every field set, and instance.field reads one. Add mut to the variable when you need to change a field.

Additional Resources​