// Example 2: Structs, impl blocks, and methods
// Struct with automatic trait derivation
@auto
struct Point {
x: int,
y: int,
}
// Impl block with associated functions and methods
impl Point {
// Associated function (constructor)
fn new(x: int, y: int) -> Point {
Point { x, y } // Struct shorthand
}
// Method with &self
fn distance_from_origin(&self) -> int {
self.x * self.x + self.y * self.y
}
// Method with &mut self
fn translate(&mut self, dx: int, dy: int) {
self.x = self.x + dx
self.y = self.y + dy
}
// Method that consumes self
fn into_tuple(self) -> (int, int) {
(self.x, self.y)
}
}
// Struct with explicit @auto traits
@auto(Debug, Clone, PartialEq)
struct Rectangle {
width: int,
height: int,
}
impl Rectangle {
fn new(width: int, height: int) -> Rectangle {
Rectangle { width, height }
}
fn area(&self) -> int {
self.width * self.height
}
fn is_square(&self) -> bool {
self.width == self.height
}
}
fn main() {
// Create points
let p1 = Point::new(3, 4)
println!("Point 1: (${p1.x}, ${p1.y})")
println!("Distance from origin: ${p1.distance_from_origin()}")
// Mutable point
let mut p2 = Point::new(0, 0)
p2.translate(5, 5)
println!("Point 2 after translation: (${p2.x}, ${p2.y})")
// Consuming self
let p3 = Point::new(1, 2)
let tuple = p3.into_tuple()
println!("As tuple: (${tuple.0}, ${tuple.1})")
// Rectangles
let rect1 = Rectangle::new(10, 20)
let rect2 = Rectangle::new(15, 15)
println!("Rectangle 1 area: ${rect1.area()}")
println!("Rectangle 1 is square: ${rect1.is_square()}")
println!("Rectangle 2 is square: ${rect2.is_square()}")
}