Rust:trait中 关联类型、泛型参数、默认参数混用

关联类型:是trait中的占位符。在内部约定一个特别的类型,和泛型似类(泛型是外部约定)
泛型参数:是指参数中,实现trait的对象类型是一个泛型类;即不特定的一类
默认参数:是指参数中,有实现trait的对象类型就是某一个特殊的类;即特定的一类

上代码:

#[derive(Debug)]
pub enum RunStrategy{
    AAAA,
    BBBB,
    CCCC,
}

pub trait Strategy< T= Vec<String>> {
    type N;
    type M;
    fn poll(&self) -> Self::N;
    fn run(&self, a:&Self::N, b:&Self::M) -> bool;
}

#[derive(Debug)]
pub struct Strategy_aaaa{
    code :String,
}
impl Strategy_aaaa{
    pub fn default()-> Self{
        Strategy_aaaa{ code:"600036".to_string()}
    }
}
impl Strategy for Strategy_aaaa{
    type N = Vec<String>;
    type M = RunStrategy;
    fn poll(&self) -> Self::N{
        vec!["600036".to_string(),"600016".to_string()]
    }
    fn run(&self,name: &Vec<String>,stra:&RunStrategy)->bool{
        println!("name :{:?} is running!",name);
        println!("strategy :{:?}",stra);
        true
    }
}

fn main(){
    println!("hello!");
    let aaaa = Strategy_aaaa::default();
    let ty   = RunStrategy::AAAA;
    println!("poll=>{:?}",aaaa.poll());
    println!("run =>{:?}",aaaa.run(&vec!["600036".to_string()],&ty));
    
}
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页