Function trait_concept

Source
pub fn trait_concept()
Expand description

§概念介绍

§trait 四种作用

  • 接口 (interface)
  • 类型标记(Mark)
  • 泛型限定(trait bound)
  • 抽象类型(trait object)

§静态分发(单态化 - Monomorphized)

use std::string::ToString;

fn print<T: ToString>(v: T) {
    println!("{}", v.to_string());
}

impl Trait语法

use std::string::ToString;

#[inline(never)]
fn print(v: &impl ToString) {
    println!("{}", v.to_string());
}

使用 impl Trait 解决问题:

// error codes:

use std::fmt::Display;

fn main() {
    println!("{}", make_value(0));
    println!("{}", make_value(1));
}

fn make_value<T: Display>(index: usize) -> T {
    match index {
        0 => "Hello, World",
        1 => "Hello, World (1)",
        _ => panic!(),
    }
}

修正:

use std::fmt::Display;

fn make_value(index: usize) -> impl Display {
    match index {
        0 => "Hello, World",
        1 => "Hello, World (1)",
        _ => panic!(),
    }
}

impl Trait 生命周期相关:


// error
fn make_debug<T>(_: T) -> impl std::fmt::Debug + 'static{
    42u8
}

// fn make_debug<'a, T: 'static>(_: &'a T) -> impl std::fmt::Debug + 'static{
//     42u8
// }

fn test() -> impl std::fmt::Debug {
    let value = "value".to_string();
    make_debug(&value)
}

实际案例 - 模版模式:https://github.com/actix/actix-extras/tree/master/actix-web-httpauth

§trait 一致性

trait 和 类型 必须有一个在本地。