Guide

Structs

A struct lets you group related values under one name.

Defining structs

List each field with its name and type. Make a value by giving every field a value. Read a field with a dot.

struct User {    name: String,    age: u32,}let u = User { name: String::from("Ana"), age: 30 };println!("{}", u.age); // 30

To change a field, the whole variable must be mut. You can't mark only one field as mutable.

Field init shorthand

When a variable has the same name as a field, write the name once. User { name, age } means User { name: name, age: age }.

Struct update syntax

..other fills every field you did not list from another value. It must come last.

let b = User { name: String::from("Bo"), ..u };

Fields are copied or moved, just like with let. If a String field is moved this way, the old value can't be used as a whole any more.

Tuple structs

A tuple struct has fields with no names. Read them with .0, .1, and so on.

struct Meters(u32);let m = Meters(5);println!("{}", m.0); // 5

Meters and Seconds(u32) are different types, even though both hold a u32. This stops you from mixing them up.

Debug printing

A struct can't be printed with {} or {:?} by default. Plain {} needs Display, which a struct does not have and which you can't derive; you write it by hand. Add #[derive(Debug)] above it to use {:?}. Use {:#?} to print one field per line.

#[derive(Debug)]struct Point { x: i32, y: i32 }println!("{:?}", Point { x: 1, y: 2 });// Point { x: 1, y: 2 }

Remember

  • Every field needs a value when you make a struct.
  • mut goes on the variable, never on one field.
  • ..other goes last and can move fields out of other.
  • Add #[derive(Debug)] to print a struct with {:?}.