[][src]Function tao_of_rust::ch03::traits::override_op

pub fn override_op()

trait 一致性

Base usage: 错误的方式,违反孤儿规则

use std::ops::Add;
impl Add<u64> for u32{
    type Output = u64;
    fn add(self, other: u64) -> Self::Output {
        (self as u64) + other
    }
}
let a = 1u32;
let b = 2u64;
assert_eq!(a+b, 3);Run

Base usage: 正确的方式之重新定义trait

trait Add<RHS=Self> {
type Output;
    fn add(self, rhs: RHS) -> Self::Output;
}
impl Add<u64> for u32{
    type Output = u64;
    fn add(self, other: u64) -> Self::Output {
        (self as u64) + other
    }
}
let a = 1u32;
let b = 2u64;
assert_eq!(a.add(b), 3);Run

Base usage: 正确的方式之重新定义类型

use std::ops::Add;
#[derive(Debug)]
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,
        }
   }
}

// Point { x: 3, y: 3 }
println!("{:?}", Point { x: 1, y: 0 } + Point { x: 2, y: 3 });Run