Rust — Structs
Basic struct
struct Person {
name: String,
age: u32,
}
fn main() {
let alice = Person {
name: String::from("Alice"),
age: 30,
};
println!("{} is {}", alice.name, alice.age);
}
Tuple structs
struct Color(u8, u8, u8);
struct Point(f64, f64);
fn main() {
let red = Color(255, 0, 0);
let origin = Point(0.0, 0.0);
println!("Red: ({}, {}, {})", red.0, red.1, red.2);
}
Unit structs
struct Marker;
fn main() {
let _m = Marker;
}
Methods
struct Rectangle {
width: f64,
height: f64,
}
impl Rectangle {
fn area(&self) -> f64 {
self.width * self.height
}
fn perimeter(&self) -> f64 {
2.0 * (self.width + self.height)
}
fn is_square(&self) -> bool {
self.width == self.height
}
}
fn main() {
let rect = Rectangle { width: 5.0, height: 3.0 };
println!("Area: {}", rect.area());
println!("Is square: {}", rect.is_square());
}
Associated functions
struct Circle {
radius: f64,
}
impl Circle {
// Associated function (like static method)
fn new(radius: f64) -> Circle {
Circle { radius }
}
fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
}
fn main() {
let c = Circle::new(5.0);
println!("Area: {:.2}", c.area());
}
Multiple impl blocks
struct Counter {
count: u32,
}
impl Counter {
fn new() -> Counter {
Counter { count: 0 }
}
}
impl Counter {
fn increment(&mut self) {
self.count += 1;
}
fn get(&self) -> u32 {
self.count
}
}
Mini Practice
Write Rust code that:
- Creates a struct with fields
- Implements methods with
&selfand&mut self - Creates an associated function
- Demonstrates tuple structs
Up Next
In the next lesson, you'll learn about Enums — enumerations in Rust.
Related Topics
Frequently Asked Questions about Structs
What is Structs in Rust?
Structs is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Structs?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Structs.
Why is Structs important in Rust?
Structs is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.