In this section, we will delve into how to use structs in Rust. Structs are a way to create custom data types that can group together related data. They are similar to classes in other programming languages but without methods. We will cover:
- Creating Instances of Structs
- Accessing Struct Fields
- Updating Structs
- Using Structs with Functions
- Destructuring Structs
- Creating Instances of Structs
To create an instance of a struct, you need to define the struct first and then instantiate it. Here’s an example:
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
fn main() {
let user1 = User {
username: String::from("user1"),
email: String::from("[email protected]"),
sign_in_count: 1,
active: true,
};
}Explanation:
- We define a struct
Userwith four fields:username,email,sign_in_count, andactive. - We create an instance of
Usernameduser1and initialize it with values.
- Accessing Struct Fields
You can access the fields of a struct using dot notation:
fn main() {
let user1 = User {
username: String::from("user1"),
email: String::from("[email protected]"),
sign_in_count: 1,
active: true,
};
println!("Username: {}", user1.username);
println!("Email: {}", user1.email);
}Explanation:
- We access the
usernameandemailfields ofuser1using dot notation and print them.
- Updating Structs
You can update the fields of a mutable struct instance:
fn main() {
let mut user1 = User {
username: String::from("user1"),
email: String::from("[email protected]"),
sign_in_count: 1,
active: true,
};
user1.email = String::from("[email protected]");
println!("Updated Email: {}", user1.email);
}Explanation:
- We declare
user1as mutable usinglet mut. - We update the
emailfield ofuser1.
- Using Structs with Functions
You can pass structs to functions and return them from functions:
fn build_user(username: String, email: String) -> User {
User {
username,
email,
sign_in_count: 1,
active: true,
}
}
fn main() {
let user1 = build_user(String::from("user1"), String::from("[email protected]"));
println!("Username: {}", user1.username);
println!("Email: {}", user1.email);
}Explanation:
- We define a function
build_userthat takesusernameandemailas parameters and returns aUserinstance. - We call
build_userinmainto createuser1.
- Destructuring Structs
You can destructure a struct to extract its fields:
fn main() {
let user1 = User {
username: String::from("user1"),
email: String::from("[email protected]"),
sign_in_count: 1,
active: true,
};
let User { username, email, sign_in_count, active } = user1;
println!("Username: {}", username);
println!("Email: {}", email);
}Explanation:
- We destructure
user1to extract its fields into separate variables.
Practical Exercise
Exercise:
- Define a struct
Bookwith fieldstitle,author,pages, andavailable. - Create an instance of
Book. - Write a function
print_book_infothat takes aBookas a parameter and prints its information. - Update the
availablefield of theBookinstance.
Solution:
struct Book {
title: String,
author: String,
pages: u32,
available: bool,
}
fn print_book_info(book: &Book) {
println!("Title: {}", book.title);
println!("Author: {}", book.author);
println!("Pages: {}", book.pages);
println!("Available: {}", book.available);
}
fn main() {
let mut book1 = Book {
title: String::from("The Rust Programming Language"),
author: String::from("Steve Klabnik and Carol Nichols"),
pages: 552,
available: true,
};
print_book_info(&book1);
book1.available = false;
println!("Updated Availability: {}", book1.available);
}Explanation:
- We define a struct
Book. - We create an instance
book1. - We define a function
print_book_infothat takes a reference to aBookand prints its fields. - We update the
availablefield ofbook1.
Conclusion
In this section, we learned how to use structs in Rust, including creating instances, accessing fields, updating fields, using structs with functions, and destructuring structs. These concepts are fundamental for organizing and managing data in Rust programs. In the next section, we will explore enums and pattern matching, which provide powerful ways to work with different types of data.
