R
Structs & Enums
Rust syntax guide
Defining custom data types with structs and enums
Structs & Enums
Defining custom data types with structs and enums
Rust structs & enums (rust)
#[derive(Debug)] // Enable debug printing
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
// Implementation block
impl Rectangle {
// Associated function (like static method)
fn square(size: u32) -> Rectangle {
Rectangle {
width: size,
height: size,
}
}
// Method
fn area(&self) -> u32 {
self.width * self.height
}
// Method that takes mutable reference
fn set_width(&mut self, width: u32) {
self.width = width;
}
// Method that takes ownership
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
// Enums
#[derive(Debug)]
enum IpAddr {
V4(String),
V6(String),
}
#[derive(Debug)]
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
// Enum with methods
impl Message {
fn call(&self) {
match self {
Message::Quit => println!("Quit"),
Message::Move { x, y } => println!("Move to {}, {}", x, y),
Message::Write(text) => println!("Write: {}", text),
Message::ChangeColor(r, g, b) => println!("Color: {},{},{}", r, g, b),
}
}
}
// Option enum (built-in)
fn find_user(id: u32) -> Option<User> {
if id == 1 {
Some(User {
username: String::from("alice"),
email: String::from("alice@example.com"),
sign_in_count: 1,
active: true,
})
} else {
None
}
}
// Result enum (built-in)
fn divide(a: f64, b: f64) -> Result<f64, String> {
if b == 0.0 {
Err(String::from("Division by zero"))
} else {
Ok(a / b)
}
}
fn main() {
// Struct usage
let mut user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
user1.email = String::from("anotheremail@example.com");
// Rectangle usage
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle::square(20); // Associated function
let rect3 = Rectangle {
width: 10,
height: 40,
};
println!("Area: {}", rect1.area());
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
println!("Can rect2 hold rect3? {}", rect2.can_hold(&rect3));
// Enum usage
let home = IpAddr::V4(String::from("127.0.0.1"));
let loopback = IpAddr::V6(String::from("::1"));
let msg1 = Message::Move { x: 10, y: 20 };
let msg2 = Message::Write(String::from("hello"));
let msg3 = Message::Quit;
msg1.call();
msg2.call();
msg3.call();
// Option usage
match find_user(1) {
Some(user) => println!("Found user: {}", user.username),
None => println!("User not found"),
}
// Result usage
match divide(10.0, 2.0) {
Ok(result) => println!("Result: {}", result),
Err(error) => println!("Error: {}", error),
}
}
Explanation
Structs allow you to create custom data types that group related values. Enums (enumerations) define a type by enumerating its possible variants, which can also hold data.
Common Use Cases
- Modeling complex data structures
- Representing different states or types of data
- Creating domain-specific types
Related Rust Syntax
Master Structs & Enums in Rust
Understanding structs & enums is fundamental to writing clean and efficient Rust code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.
Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using structs & enums effectively in your Rust projects.
Key Takeaways
- Modeling complex data structures
- Representing different states or types of data
- Creating domain-specific types