Rust Structs Explained - Custom Data Types, Methods & Derive Traits | Rust Tutorial
Video: Rust Structs Explained - Custom Data Types, Methods & Derive Traits | Rust Tutorial by Taught by Celeste AI - AI Coding Coach
Watch full page →Rust Structs Explained - Custom Data Types, Methods & Derive Traits
Structs in Rust allow you to create custom data types by grouping related fields together, making your code more organized and expressive. This tutorial demonstrates how to define structs, add methods using impl blocks, and automatically implement useful traits with #[derive].
Code
// Define a basic struct to group related data
struct Person {
name: String,
age: u32,
}
// Define a struct with methods using an impl block
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
// Method to calculate the area of the rectangle
fn area(&self) -> u32 {
self.width * self.height
}
// Associated function (constructor) to create a new Rectangle
fn new(width: u32, height: u32) -> Rectangle {
Rectangle { width, height }
}
}
// Derive traits to automatically implement Debug, Clone, PartialEq
#[derive(Debug, Clone, PartialEq)]
struct Point {
x: i32,
y: i32,
}
fn main() {
// Create an instance of Person
let person = Person {
name: String::from("Alice"),
age: 30,
};
println!("{} is {} years old.", person.name, person.age);
// Create a Rectangle instance using the constructor
let rect = Rectangle::new(10, 5);
println!("Rectangle area: {}", rect.area());
// Create and clone a Point instance
let point1 = Point { x: 3, y: 4 };
let point2 = point1.clone();
// Print point using Debug trait
println!("Point1: {:?}", point1);
// Compare points using PartialEq trait
println!("Points equal? {}", point1 == point2);
}
Key Points
- Structs group related data fields into a single custom type for better code organization.
- The
implblock allows you to add methods and associated functions to structs. - The
&selfparameter in methods provides access to the instance's data. #[derive]automatically implements common traits likeDebug,Clone, andPartialEq.- Associated functions like
newact as constructors to create struct instances cleanly.