Rust Lang Book Ch.19 Placeholder type, Default generic type parameter, operator overloading

Placeholder Types

在trait定义中,可以使用Associated types在定义中放一些type placeholder,并用这些type placeholder作为返回值,参数等描述类型之间的关系。接着,trait的实现中就可以将这些type placehold设置为具体类型。

定义:

pub trait Iterator {
    type Item;

    fn next(&mut self) -> Option<Self::Item>;
}

  

实现

impl Iterator for Counter {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {

  

它与直接全部使用泛型的实现不同的是,使用type placeholder只能定义一种,泛型却可以根据type parameters得到多种实现。

pub trait Iterator<T> {
    fn next(&mut self) -> Option<T>;
}

  

Default Generic Type Parameters

基本语法 type <PlaceholderType>=<ConcreteType>;

impl Iterator for Counter {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {

  

重载操作符

可以重载std::ops中的操作符

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,
        }
    }
}

  

posted @ 2020-10-28 00:38  雪溯  阅读(73)  评论(0编辑  收藏  举报