Structs Basics
9 examples to get you started with structs - 6 basic and 3 intermediate.
Busca en todas las páginas de la documentación
9 examples to get you started with structs - 6 basic and 3 intermediate.
struct User {
id: u64,
active: bool,
}
fn main() {
let u = User { id: 1, active: true };
println!("{} {}", u.id, u.active);
}u.idRelated: Methods & Associated Functions
struct Point { x: i32, y: i32 }
fn main() {
let x = 3;
let y = 4;
let p = Point { x, y };
println!("({}, {})", p.x, p.y);
}Point { x, y } expands to Point { x: x, y: y }struct Meters(f64);
fn main() {
let d = Meters(10.0);
println!("{}", d.0);
}.0, .1, ...f64 despite same representationstruct Marker;
fn main() {
let _m = Marker;
}PhantomData often preferred for generic markersstruct Config { host: String, port: u16 }
fn main() {
let base = Config { host: "localhost".into(), port: 8080 };
let alt = Config { port: 3000, ..base };
println!("{}:{}", alt.host, alt.port);
}..base copies remaining fields from basebase is moved field-by-field into alt for unspecified fieldshost, base.host is invalidstruct Counter { value: u32 }
fn main() {
let mut c = Counter { value: 0 };
c.value += 1;
println!("{}", c.value);
}mut on binding allows mutating fieldsmut in struct defCell/RefCell for shared handlesstruct Excerpt<'a> {
text: &'a str,
}
fn main() {
let article = String::from("Hello");
let e = Excerpt { text: &article };
println!("{}", e.text);
}Excerpt cannot outlive articleString field would not need 'a#[derive(Debug)]#[derive(Debug)]
struct Event { kind: u32, ts: u64 }
fn main() {
println!("{:?}", Event { kind: 1, ts: 99 });
}Debug enables {:?} printingDisplay needs manual impl)struct Pair { a: i32, b: i32 }
fn sum(Pair { a, b }: Pair) -> i32 {
a + b
}
fn main() {
println!("{}", sum(Pair { a: 2, b: 3 }));
}let and fn paramslet Pair { a, .. } = p ignores rest with ..match armsRelated: Structs & Enums Best Practices
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 19 jul 2026