zoukankan      html  css  js  c++  java
  • 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,
            }
        }
    }
    

      

  • 相关阅读:
    3.2 线程复用:线程池
    3.1.7 线程阻塞工具类:LockSupport
    3.1.6 循环栅栏:CyclicBarrier
    3.1.4 读写锁
    3.1.5 倒计时器:CountDownLatch
    3.1.3 允许多个线程同时访问:信号量
    3.1.2 condition 条件
    3.1.1 重入锁 以及源码分析
    2.8.4 错误的加锁
    jsp中 scope="application" 表示
  • 原文地址:https://www.cnblogs.com/xuesu/p/13888651.html
Copyright © 2011-2022 走看看