Types
This commit is contained in:
58
src/main.rs
58
src/main.rs
@@ -18,9 +18,9 @@ impl Add for Point {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug, PartialEq)]
|
||||||
struct Millimeters(u32);
|
struct Millimeters(u32);
|
||||||
#[derive(Debug)]
|
#[derive(Debug, PartialEq)]
|
||||||
struct Meters(u32);
|
struct Meters(u32);
|
||||||
|
|
||||||
impl Add<Meters> for Millimeters {
|
impl Add<Meters> for Millimeters {
|
||||||
@@ -31,6 +31,52 @@ impl Add<Meters> for Millimeters {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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() {
|
fn main() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
|
Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
|
||||||
@@ -40,6 +86,12 @@ fn main() {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
Millimeters(1001),
|
Millimeters(1001),
|
||||||
Millimeters(1) + Meters(1)
|
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());
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user