rust / beginner
Snippet
Defining Structs and Creating Instances
Structs are custom data types that group related fields together. Here we define a User struct with three fields, then create an instance by specifying each field's value. Field access uses dot notation.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct User {username: String,email: String,active: bool,}fn main() {let user1 = User {username: String::from("alice"),active: true,};println!("User: {} ({})", user1.username, user1.email);}
Breakdown
1
struct User { ... }
Defines a struct named User with three fields
2
username: String,
Field named username of type String
3
let user1 = User { ... };
Creates a new User instance with specific values
4
user1.username
Accesses the username field using dot notation