98 lines
1.5 KiB
Rust
98 lines
1.5 KiB
Rust
use std::ops::Add;
|
|
|
|
#[derive(Debug, PartialEq)]
|
|
struct Point {
|
|
x: i32,
|
|
y: i32,
|
|
}
|
|
|
|
impl Add for Point {
|
|
type Output = Point;
|
|
|
|
fn add(self, other: Point) -> Point {
|
|
Point {
|
|
x: self.x + other.x,
|
|
y: self.y + other.y,
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
#[derive(Debug, PartialEq)]
|
|
struct Millimeters(u32);
|
|
#[derive(Debug, PartialEq)]
|
|
struct Meters(u32);
|
|
|
|
impl Add<Meters> for Millimeters {
|
|
type Output = Millimeters;
|
|
|
|
fn add(self, other: Meters) -> Millimeters {
|
|
Millimeters(self.0 + (other.0 * 1000))
|
|
}
|
|
}
|
|
|
|
trait Pilot {
|
|
fn fly(&self);
|
|
}
|
|
|
|
trait Wizard {
|
|
fn fly(&self);
|
|
}
|
|
|
|
struct Human;
|
|
|
|
impl Pilot for Human {
|
|
fn fly(&self) {
|
|
println!("This is your captain speaking.");
|
|
}
|
|
}
|
|
|
|
impl Wizard for Human {
|
|
fn fly(&self) {
|
|
println!("Up!");
|
|
}
|
|
}
|
|
|
|
impl Human {
|
|
fn fly(&self) {
|
|
println!("*waving arms furiously*");
|
|
}
|
|
}
|
|
|
|
trait Animal {
|
|
fn baby_name() -> String;
|
|
}
|
|
|
|
struct Dog;
|
|
|
|
impl Dog {
|
|
fn baby_name() -> String {
|
|
String::from("Spot")
|
|
}
|
|
}
|
|
|
|
impl Animal for Dog {
|
|
fn baby_name() -> String {
|
|
String::from("puppy")
|
|
}
|
|
}
|
|
|
|
fn main() {
|
|
assert_eq!(
|
|
Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
|
|
Point { x: 3, y: 3 }
|
|
);
|
|
|
|
assert_eq!(
|
|
Millimeters(1001),
|
|
Millimeters(1) + Meters(1)
|
|
);
|
|
|
|
let person = Human;
|
|
person.fly();
|
|
Pilot::fly(&person);
|
|
Wizard::fly(&person);
|
|
|
|
println!("A baby dog is called a {}", <Dog as Animal>::baby_name());
|
|
}
|