Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Keywords and Statements

The struct keyword

Reference for Rust struct: named-field, tuple and unit structs, construction and field init shorthand, update syntax, visibility, derives and memory layout.

A struct groups values into one named type. Rust has three flavors: named-field structs (struct Point { x: i32, y: i32 }), tuple structs whose fields are positional (struct Meters(f64);), and unit structs with no fields at all (struct Marker;). Methods and trait implementations are attached separately with impl.

Fields are private to the module that defines the struct unless marked pub, which makes structs the main tool for encapsulation. Tuple structs with one field (the newtype pattern) give a distinct type to an existing one, so a UserId(u64) cannot be confused with an OrderId(u64).

Rust
struct User { name: String, age: u32 }
let u = User { name: String::from("Ann"), age: 30 };

Try it

Rust Three kinds of 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.

Rust Update syntax, Default and private fields

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.

Syntax

Rust
struct Name { field: Type, pub other: Type }     // named fields
struct Name(Type, Type);                        // tuple struct
struct Name;                                    // unit struct
struct Wrapper<T> { inner: T }                  // generic
struct Ref<'a> { text: &'a str }                // with a lifetime

let v = Name { field: 1, other: 2 };
let v = Name { field, ..other };                // struct update
Part Description
Fields Each has a name (or position) and a type. A field may be pub, pub(crate) or private.
Init shorthand Name { x, y } when local variables have the same names as the fields.
..base Fills the remaining fields from base; fields that are not Copy are moved out of it.
#[derive(...)] Auto-implements traits such as Debug, Clone, PartialEq, Default, Hash.

Errors: a missing field in a literal is E0063; accessing a private field from another module is E0616; using a struct after a field was moved by ..base may give E0382.

Usage notes

  • Initialize every field. There are no default values for fields; use #[derive(Default)] and ..Default::default() for optional-style construction.
  • Methods go in impl blocks. Structs themselves hold only data.
  • Size and layout: the Rust compiler may reorder fields to reduce padding. Use #[repr(C)] for a C-compatible layout, and #[repr(transparent)] for a newtype with the same layout as its field.
  • Unit and zero-sized structs take no memory; they are used for markers, type-state and implementing traits on nothing.
  • Mutability is per binding, not per field: let mut p makes all fields assignable; there is no field-level mut.
  • Borrowing fields independently works within one function: &mut s.a and &mut s.b can coexist, but method calls borrow the whole struct.
  • Private fields block the literal. Outside the defining module you cannot write Name { a, ..other } if any omitted field is private (E0451); offer a constructor or builder instead.
  • Fields that hold references need lifetime parameters. Prefer owned fields (String, Vec<T>) until you have a reason to borrow.
  • Derive order does not matter, but deriving Eq/Ord/Hash requires all fields to support them.
  • Pattern matching works on structs: let Point { x, .. } = p;.