Struct Initialization
Constructing an instance of a struct in Rust uses a struct literal expression (StructName { field1: val1, field2: val2 }) that supplies an initial value for every declared field of the struct.
Explicit Field Initialization and Field Order
Fields in a struct initializer can be written in any order, regardless of the order in which they were declared in the struct definition, and every field is evaluated in the top-to-bottom order written in the literal:
#[derive(Debug)]
struct ServerConfig {
host: String,
port: u16,
workers: usize,
}
fn main() {
let cfg = ServerConfig {
port: 8080,
workers: 4,
host: String::from("127.0.0.1"),
};
println!("{cfg:?}");
}
ServerConfig { host: "127.0.0.1", port: 8080, workers: 4 }
Field Init Shorthand (field Instead of field: field)
When a local variable or function parameter has the exact same name as a struct field, Rust's field init shorthand lets you write the identifier once (host) instead of repeating host: host:
#[derive(Debug)]
struct User {
username: String,
email: String,
active: bool,
}
fn create_user(username: String, email: String) -> User {
User {
username, // Shorthand for `username: username`
email, // Shorthand for `email: email`
active: true,
}
}
fn main() {
let u = create_user(String::from("ferris"), String::from("ferris@rust-lang.org"));
println!("Created: {} <{}> (active={})", u.username, u.email, u.active);
}
Created: ferris <ferris@rust-lang.org> (active=true)
Initializing via Default (#[derive(Default)])
For structs whose fields all have sensible default values (0 for numbers, false for bool, "" for String, empty Vec, None for Option), deriving Default provides Type::default():
#[derive(Debug, Default)]
struct RenderOptions {
width: u32,
height: u32,
fullscreen: bool,
title: String,
}
fn main() {
let defaults = RenderOptions::default();
println!("Default options: {defaults:?}");
}
Default options: RenderOptions { width: 0, height: 0, fullscreen: false, title: "" }
Privacy Constraint on Struct Literals (E0451)
A struct literal StructName { ... } can only be constructed directly if all of its fields are visible (pub) in the current scope. If even one field is private to another module, external code must call a public constructor function (such as StructName::new(...)) defined inside that module (E0451: field is private).