capypad
0 day streak
rust / beginner
Snippet

Defining and Using Structs

Structs are custom data types that group related fields together. They work like blueprints for creating objects. Here we define a User struct with three fields, create instances using named fields, and use the struct update syntax (..) to copy remaining fields from another instance.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct User {
username: String,
email: String,
active: bool,
}
 
fn main() {
let user1 = User {
username: String::from("alice"),
email: String::from("[email protected]"),
active: true,
};
println!("User: {} ({})", user1.username, user1.email);
let mut user2 = User {
username: String::from("bob"),
..user1
};
user2.active = false;
println!("User 2 active: {}", user2.active);
}
Breakdown
1
struct User {
Defines a struct named User with three fields
2
username: String,
A username field of type String
3
let user1 = User { ... };
Creates a User instance using field init syntax
4
..user1
Struct update syntax - copies remaining fields from user1