Data Structures:
Structs:
Structs allow you to create custom data types by grouping related data fields together. Each field can have its own data type, and you can define methods associated with the struct.
Simple Example:
code
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 10, y: 20 };
println!("Point coordinates: ({}, {})", p.x, p.y);
}
Complex Example:
code
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect = Rectangle { width: 10, height: 20 };
println!("Area of rectangle: {}", rect.area());
}
Enums:
Enums allow you to define a type by enumerating its possible variants. Each variant can optionally contain data of different types.
Simple Example:
code
enum TrafficLight {
Red,
Yellow,
Green,
}
fn main() {
let light = TrafficLight::Red;
match light {
TrafficLight::Red => println!("Stop"),
TrafficLight::Yellow => println!("Caution"),
TrafficLight::Green => println!("Go"),
}
}
Complex Example:
code
enum Shape {
Circle(f64),
Rectangle(f64, f64),
Triangle(f64, f64, f64),
}
impl Shape {
fn area(&self) -> f64 {
match *self {
Shape::Circle(radius) => std::f64::consts::PI * radius * radius,
Shape::Rectangle(width, height) => width * height,
Shape::Triangle(a, b, c) => {
let s = (a + b + c) / 2.0;
(s * (s - a) * (s - b) * (s - c)).sqrt()
}
}
}
}
fn main() {
let circle = Shape::Circle(5.0);
let rectangle = Shape::Rectangle(4.0, 6.0);
let triangle = Shape::Triangle(3.0, 4.0, 5.0);
println!("Area of circle: {}", circle.area());
println!("Area of rectangle: {}", rectangle.area());
println!("Area of triangle: {}", triangle.area());
}
Collections:
Rust's standard library provides several collection types, including Vec (vector), HashMap, HashSet, and more. These collections allow you to store and manipulate data in various ways.
Simple Example:
code
fn main() {
let mut numbers = Vec::new();
numbers.push(1);
numbers.push(2);
numbers.push(3);
println!("Numbers: {:?}", numbers);
}
Complex Example:
code
use std::collections::HashMap;
fn main() {
let mut population = HashMap::new();
population.insert("Tokyo", 13929286);
population.insert("New York", 8550405);
population.insert("London", 8908081);
for (city, pop) in &population {
println!("{} has a population of {}", city, pop);
}
}
In the next section, we'll explore error handling and concurrency in Rust.