use std::ops;
use RustBook_Instances_CN::tools::print_line;
use std::fmt;
pub fn enter(){
default_generic_param_and_operator_overloading();
print_line();
fully_qualified_syntax();
print_line();
super_trait();
print_line();
new_type();
}
pub trait Iterator{
type Returned_U32;
fn next(&mut self)->Option<Self::Returned_U32>;
}
struct Counter{
}
impl Iterator for Counter{
type Returned_U32 = u32;
fn next(&mut self)->Option<Self::Returned_U32>{
return Some(1);
}
}
fn default_generic_param_and_operator_overloading(){
let p1 = Point{x:1,y:0};
let p2 = Point{x:2,y:3};
assert_eq!(
Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
Point { x: 3, y: 3 }
);
println!("p1 + p2 = {:?}",p1+p2);
}
#[derive(Debug,Copy,Clone,PartialEq)]
struct Point{
x:i32,
y:i32,
}
impl ops::Add for Point{
type Output = Point;
fn add(self,other:Point)->Point{
return Point{
x:self.x+other.x,
y:self.y+other.y,
};
}
}
struct Millimeters(u32);
struct Meters(u32);
impl ops::Add for Millimeters{
type Output = Millimeters;
fn add(self,other:Millimeters)->Millimeters{
return Millimeters(self.0+other.0);
}
}
fn fully_qualified_syntax(){
let human = Human;
human.fly();
let person = Human;
Pilot::fly(&person);
Wizard::fly(&person);
person.fly();
println!("a baby dog is called a {}",Dog::baby_name());
println!("a baby dog is called a {}",<Dog as Animal>::baby_name());
}
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 super_trait(){
}
trait OutlinePrint: fmt::Display{
fn outline_print(&self){
let output = self.to_string();
let len = output.len();
println!("{}", "*".repeat(len + 4));
println!("*{}*", " ".repeat(len + 2));
println!("* {} *", output);
println!("*{}*", " ".repeat(len + 2));
println!("{}", "*".repeat(len + 4));
}
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
fn new_type(){
let w = Wrapper(vec![String::from("hello"), String::from("world")]);
println!("w = {}", w);
}
struct Wrapper(Vec<String>);
impl fmt::Display for Wrapper {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{}]", self.0.join(", "))
}
}