Structs and Enums
User-defined types with structs, enums, and impl blocks. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Search across all documentation pages
User-defined types with structs, enums, and impl blocks. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Define fields and construct with field init shorthand.
struct User { id: u32, name: String }
let u = User { id: 1, name: "Ada".into() };
u.id // 1Copy remaining fields from another instance with ...
#[derive(Clone)]
struct Cfg { host: String, port: u16 }
let a = Cfg { host: "x".into(), port: 80 };
let b = Cfg { port: 443, ..a.clone() };
b.port // 443Newtypes and lightweight products without field names.
struct Meters(f64);
let m = Meters(1.5);
m.0 // 1.5Zero-sized marker types with no fields.
struct Marker;
let _m = Marker; // unit-likeEnums hold one of several variants, optionally with data.
enum Msg { Quit, Move { x: i32, y: i32 }, Write(String) }
let m = Msg::Move { x: 1, y: 2 };
matches!(m, Msg::Move { .. }) // trueMethods take self, &self, or &mut self.
struct Counter { n: i32 }
impl Counter {
fn inc(&mut self) { self.n += 1; }
fn get(&self) -> i32 { self.n }
}
let mut c = Counter { n: 0 };
c.inc();
c.get() // 1Constructors like new take no self.
struct Point { x: i32, y: i32 }
impl Point {
fn origin() -> Self { Self { x: 0, y: 0 } }
}
Point::origin().x // 0Option<T> is either Some(v) or None.
let x: Option<i32> = Some(3);
x.unwrap_or(0) // 3
None::<i32>.unwrap_or(0) // 0Result<T, E> is Ok(v) or Err(e).
let r: Result<i32, &str> = Ok(1);
r.unwrap_or(-1) // 1impl blocks work on enums too.
enum Traffic { Red, Green }
impl Traffic {
fn can_go(&self) -> bool { matches!(self, Traffic::Green) }
}
Traffic::Green.can_go() // trueDot access for named fields; tuple index for tuple structs.
struct P { x: i32 }
P { x: 9 }.x // 9#[derive(Debug)] enables {:?} formatting.
#[derive(Debug)]
struct P { x: i32 }
format!("{:?}", P { x: 1 }) // "P { x: 1 }"Equality for tests and compares.
#[derive(PartialEq)]
struct P { x: i32 }
P { x: 1 } == P { x: 1 } // trueDefault for zero values and ..Default::default().
#[derive(Default)]
struct Cfg { port: u16 }
Cfg::default().port // 0Wrap primitives for type safety.
struct UserId(u64);
let id = UserId(42);
id.0 // 42Stack versions: Rust 1.97.0 · edition 2024 · Tokio 1.x · serde 1.0
Reviewed by Chris St. John·Last updated Jul 18, 2026