Rust:特征对象

5 阅读1分钟

示例

    struct Button{
        label:String,
    }
    impl Button{
        fn on_click(){
            println!("点击事件");
        }
    }
    trait Draw{
        fn draw(&self);
    }
    
    impl Draw for Button(){
        fn draw(&self){
            println!("绘制按钮")
        }
    }
    
    trait Other{
        fn other_method(&self);
    }
    
    impl Other for Button(){
        fn other(&self){
            println!("实现的其他特征方法");
        }
    }

@ 当类型实现了特征时,类型的实例对象可当作特征的特征对象使用

意思就是

    let b:Button = Button{label:String::from("按钮1")};
    
    let b_draw_trait_object &dyn Draw = &b; //b 当作Draw特征的特征对象
    let b_other_trait_object &dyn Other = &b;

@ 特征对象只能调用 实现了特征的方法,不能调用实例本身的方法和实现了其他特征的方法

意思就是

    b_draw_trait_object.on_click() //b本身的也不行
    b_draw_trait_object.other() //other特征实现的方法也不行
    
    b.on_click()//可以
    b_draw_trait_object.draw() //可以
    b_other_trait_object.other() //可以

@ 定义组合特征 可以访问多个特征的方法了

意思就是

    //以下代码为个人理解 未验证
    impl Combtrait Draw + Other {}
    impl Combtrait for Button{}
    
    let b_comb: &dyn Combtrait = &b;
    
    b_comb.draw();//可以
    b_comb.other();//可以

@ 特征对象有啥子用?

1、允许动态分发 运行时多态

2、可以将不同类型的对象放入同一集合

3、实现了针对接口编程