Defining and Instantiating Structs
Structs provide named fields for data grouping, offering better semantics than tuples when field order shouldn’t matter.
Basic Syntax
struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn main() {}
Instantiation uses key-value pairs in any order:
struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn main() { let user1 = User { active: true, username: String::from("someusername123"), email: String::from("someone@example.com"), sign_in_count: 1, }; }
Access and mutation require the entire instance to be mutable:
struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn main() { let mut user1 = User { active: true, username: String::from("someusername123"), email: String::from("someone@example.com"), sign_in_count: 1, }; user1.email = String::from("anotheremail@example.com"); }
Functions can return struct instances as the last expression:
struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn build_user(email: String, username: String) -> User { User { active: true, username: username, email: email, sign_in_count: 1, } } fn main() { let user1 = build_user( String::from("someone@example.com"), String::from("someusername123"), ); }
Field Init Shorthand
When parameter names match field names, use shorthand syntax:
struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn build_user(email: String, username: String) -> User { User { active: true, username, email, sign_in_count: 1, } } fn main() { let user1 = build_user( String::from("someone@example.com"), String::from("someusername123"), ); }
Struct Update Syntax
Create instances from existing ones with selective field updates:
struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn main() { // --snip-- let user1 = User { email: String::from("someone@example.com"), username: String::from("someusername123"), active: true, sign_in_count: 1, }; let user2 = User { active: user1.active, username: user1.username, email: String::from("another@example.com"), sign_in_count: user1.sign_in_count, }; }
The ..
operator copies remaining fields:
struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn main() { // --snip-- let user1 = User { email: String::from("someone@example.com"), username: String::from("someusername123"), active: true, sign_in_count: 1, }; let user2 = User { email: String::from("another@example.com"), ..user1 }; }
Ownership Note: Struct update uses move semantics. If any moved field contains non-Copy data (like String
), the original instance becomes unusable. Fields implementing Copy
(like primitives) are copied, not moved.
Tuple Structs
Tuple structs provide struct semantics with positional fields:
struct Color(i32, i32, i32); struct Point(i32, i32, i32); fn main() { let black = Color(0, 0, 0); let origin = Point(0, 0, 0); }
Different tuple struct types are incompatible even with identical field types. Access uses dot notation with indices: origin.0
, origin.1
, etc.
Unit-Like Structs
Structs without fields are useful for trait implementations without data:
struct AlwaysEqual; fn main() { let subject = AlwaysEqual; }
Ownership in Structs
Structs typically own their data using owned types like String
rather than references like &str
. References in structs require lifetime parameters:
struct User {
active: bool,
username: &str, // Error: missing lifetime specifier
email: &str, // Error: missing lifetime specifier
sign_in_count: u64,
}
fn main() {
let user1 = User {
active: true,
username: "someusername123",
email: "someone@example.com",
sign_in_count: 1,
};
}
Compiler output:
$ cargo run
Compiling structs v0.1.0 (file:///projects/structs)
error[E0106]: missing lifetime specifier
--> src/main.rs:3:15
|
3 | username: &str,
| ^ expected named lifetime parameter
|
help: consider introducing a named lifetime parameter
|
1 ~ struct User<'a> {
2 | active: bool,
3 ~ username: &'a str,
|
error[E0106]: missing lifetime specifier
--> src/main.rs:4:12
|
4 | email: &str,
| ^ expected named lifetime parameter
|
help: consider introducing a named lifetime parameter
|
1 ~ struct User<'a> {
2 | active: bool,
3 | username: &str,
4 ~ email: &'a str,
|
For more information about this error, try `rustc --explain E0106`.
error: could not compile `structs` (bin "structs") due to 2 previous errors
Lifetimes are covered in Chapter 10. For now, use owned types to avoid complexity.