rust / beginner
Snippet
Basic Structs in Rust
Structs are custom data types that let you package related values together. They are similar to classes in other languages but without methods. In this example, we define a User struct with three fields. Instances are created using struct literal syntax. The entire struct can be made mutable with mut, and individual fields are accessed using dot notation.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
struct User {username: String,email: String,active: bool,}fn main() {let user1 = User {username: String::from("testuser"),active: true,};println!("User: {} ({})", user1.username, user1.email);let mut user2 = user1;user2.username = String::from("newuser");println!("Updated: {}", user2.username);}
Breakdown
1
struct User {
Defines a new struct type named User
2
username: String,
Field storing the username as a String
3
let user1 = User { ... };
Creates an instance of User struct
4
let mut user2 = user1;
Ownership moves to user2, making user1 invalid
5
user2.username = ...
Modifies the username field since user2 is mutable