• rust特性


    trait可以翻译成特性、特质、特征。
    trait是一种特殊的类型,用于抽象某些方法。trait类似于其他编程语言中的接口。
    trait定义了一组方法,其他类型可以各自实现这个trait的方法,从而形成多态。

    一、定义trait

    (一)使用trait关键字
    语法格式

    trait trait_name{
        fn fn1(&self);
        fn fn2(&self);
        //...
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    其中包含一组方法。
    方法第一个参数必须是&self。

    例子

    trait MyTrait {
         fn do_something(&self);
    }
    
    • 1
    • 2
    • 3

    方法可以有默认实现,如果其他类型实现trait时不覆盖这些方法,将使用默认实现。
    例子

    trait MyTrait {
         fn do_something(&self) {
             // 默认实现
         }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    (二)trait继承
    trait可以继承其他trait
    语法格式

    trait trait_name: parent_trait_name{
        fn fn1(&self);
    }
    
    • 1
    • 2
    • 3

    例子

    trait Printable {
         fn print(&self);
    }
    trait Debuggable: Printable {
         fn debug(&self);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    Debuggable继承了Printable,从而Debuggable包含了Printable中的方法。

    多继承
    例子

    trait Paginate: Page + PerPage { 
         fn set_skip_page(&self, num: i32){
             println!("Skip Page: {:?}", num);
         }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    (三)关联类型
    关联类型是一个类型占位符。当实现trait时才指定具体类型。
    在trait定义里,使用type关键字。
    语法格式

    trait xx {
         type T;
    }
    
    • 1
    • 2
    • 3

    例子
    标准库提供的Iterator trait有一个关联类型Item

    pub trait Iterator {
         type Item;
         fn next(&mut self) -> Option;
    }
    impl Iterator for Counter {
         type Item = u32;
         fn next(&mut self) -> Option {
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    Item是一个类型占位符,next方法返回Option 类型的值。这个trait的实现者会指定Item的具体类型。

    关联类型看起来像泛型,都是在定义时不指定具体类型。那么为什么不直接使用泛型呢?比如下面这样

    pub trait Iterator {
         fn next(&mut self) -> Option;
    }
    
    • 1
    • 2
    • 3

    区别在于当trait有泛型参数时,一个类型可以多次实现这个trait,每次为泛型参数指定不同的具体类型。比如Iterator for Counter,Iterator for Counter,Iterator for Counter。Counter有多个Iterator的实现。
    接着当使用Counter的next方法时,必须标明使用哪一个Iterator实现。比如Counter.next(),Counter.next(),Counter.next()
    通过关联类型,则无需标注类型,因为只能实现一次这个trait。只能有一个impl Iterator for Counter。当调用Counter的next时不必每次指定我们需要u32值的迭代器。

    二、实现trait

    (一)为某个类型实现trait
    使用impl关键字。
    语法格式

    impl trait_name for type{
        fn fn1(&self);
        fn fn2(&self);
        //...
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    例子

    trait MyTrait {
         fn do_something(&self);
    }
    struct MyStruct;
    impl MyTrait for MyStruct {
         fn do_something(&self) {
              // 实现方法逻辑
         }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在上述例子中,我们为MyStruct类型实现了MyTrait。

    (二)在外部类型上实现外部trait
    孤儿规则是指trait或类型处于当前crate时才可以在此类型上实现该trait。这意味着无法在外部类型上实现外部trait。一个绕开这个限制的方法是使用newtype模式。
    newtype模式是使用元组结构体创建一个新类型,这个元组结构体只有一个字段,相当于对这个字段类型的封装。这样这个新类型就处于当前crate了,就可以为这个新类型实现trait。Newtype是一个源自Haskell编程语言的概念。使用这个模式没有运行时性能消耗,这个封装类型在编译时就被省略了。
    例如,想要在Vec 上实现Display,因为Display trait和Vec 都定义于我们的crate之外,所以无法这么做。可以创建一个包含Vec 的元组结构体,接着为元组结构体实现Display并使用Vec 的值:

    use std::fmt;
    struct Wrapper(Vec);
    impl fmt::Display for Wrapper {
         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
             write!(f, "[{}]", self.0.join(", "))
         }
    }
    fn main() {
         let w = Wrapper(vec![String::from("hello"), String::from("world")]);
         println!("w = {}", w);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    使用self.0来访问其内部的Vec,因为Wrapper是元组结构体而Vec 是结构体总位于索引0的项。
    因为Wrapper是一个新类型,它没有内部类型的方法。如果希望新类型拥有其内部类型的每一个方法,那么可以为新类型实现Deref trait并返回其内部类型。如果不希望新类型拥有所有内部类型的方法,那么必须自行实现所需的方法。

    三、使用trait

    (一)trait作为函数的参数
    trait可以作为函数的参数类型

    例子

    fn output(object: impl Descriptive) {
         println!("{}", object.describe());
    }
    
    • 1
    • 2
    • 3

    任何实现了Descriptive的实例都可以作为这个函数的参数

    例子

    trait Drawable {
         fn draw(&self);
    }
    fn draw_shape(shape: &impl Drawable) {
         shape.draw();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    函数draw_shape,它接受实现了Drawable的类型作为参数。

    如果涉及多个特性,可以用 + 符号表示,例如:

    fn notify(item: impl Summary + Display)
    
    • 1

    (二)trait作为返回值
    trait可以作为函数的返回值类型
    格式如下:

    fn person() -> impl Descriptive {
        //
    }
    
    • 1
    • 2
    • 3

    例子

    fn returns_summarizable() -> impl Summary {
         Tweet {
             username: String::from("horse_ebooks"),
             content: String::from( "of course, as you probably already know, people", ),
             reply: false, retweet: false,
         }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    returns_summarizable函数返回某个实现了Summary的类型的实例。在这个例子中返回了一个 Tweet,不过调用方并不知情。

    特性做返回值,所有返回支返回值类型必须完全一样
    比如下面这个函数就是错误的:
    实例

    fn some_function(bool bl) -> impl Descriptive {
        if bl {
            return StructA {};
        } else {
            return StructB {};
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  • 相关阅读:
    基础会计学重点
    内存管理(三)——内存分页
    CentOS7.9安装
    Liunx 部署后端服务jar包脚本
    uniapp列表进入动画
    根据前序中序求后序
    CSS---div盒子模型、相对绝对位置、float浮动、清除浮动
    刷题神器!把LeetCode题目生成卡片;苏黎世联邦理工『数据科学数学基础』课程;深度学习实例锦囊(含代码) ;前沿论文 | ShowMeAI资讯日报
    QT中使用unity
    408-2015
  • 原文地址:https://blog.csdn.net/inxunxun/article/details/133191710