You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Structs and enums are Rust's primary tools for creating custom data types. Combined with pattern matching, they form a powerful and expressive type system.
A struct groups related data together:
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
let user1 = User {
username: String::from("alice"),
email: String::from("alice@example.com"),
sign_in_count: 1,
active: true,
};
When variable names match field names:
fn build_user(email: String, username: String) -> User {
User {
email, // shorthand for email: email
username, // shorthand for username: username
active: true,
sign_in_count: 1,
}
}
Create a new struct based on an existing one:
let user2 = User {
email: String::from("bob@example.com"),
..user1 // remaining fields from user1
};
Tip: The
..user1syntax moves any non-Copy fields fromuser1. After this,user1.usernameis no longer valid (it was moved), butuser1.activeanduser1.sign_in_countare still valid (they are Copy types).
Named tuples with struct semantics:
struct Colour(i32, i32, i32);
struct Point(f64, f64, f64);
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.