Defining a Struct
#[derive(Debug)]
struct User {
username: String,
email: String,
active: bool,
sign_in_count: u64,
}
let user1 = User {
email: String::from("alice@example.com"),
username: String::from("alice"),
active: true,
sign_in_count: 1,
};
println!("{}", user1.username);
println!("{:?}", user1); // debug print
Methods with impl
struct Rectangle {
width: f64,
height: f64,
}
impl Rectangle {
// Constructor (associated function, no self)
fn new(width: f64, height: f64) -> Rectangle {
Rectangle { width, height }
}
// Method (takes &self)
fn area(&self) -> f64 {
self.width * self.height
}
fn is_square(&self) -> bool {
self.width == self.height
}
}
let rect = Rectangle::new(5.0, 3.0);
println!("Area: {}", rect.area()); // 15
println!("Square: {}", rect.is_square()); // false
Traits — shared behavior
trait Greet {
fn greeting(&self) -> String;
fn greet(&self) {
println!("{}", self.greeting()); // default implementation
}
}
struct English;
struct Spanish;
impl Greet for English {
fn greeting(&self) -> String {
String::from("Hello!")
}
}
impl Greet for Spanish {
fn greeting(&self) -> String {
String::from("¡Hola!")
}
}
English.greet(); // Hello!
Spanish.greet(); // ¡Hola!
Common derive macros
#[derive(Debug, Clone, PartialEq)]
struct Point {
x: f64,
y: f64,
}
let p1 = Point { x: 1.0, y: 2.0 };
let p2 = p1.clone();
println!("{:?}", p1); // Point { x: 1.0, y: 2.0 }
println!("Equal: {}", p1 == p2); // true