Rust : Trait Object 、vec![]和Vec::new()与Send,Sync

2020/09/04 07:09
阅读数 1.5K

碰到这种情况,代码如下:

#[derive(Clone)]
struct Trade(i32);
trait Bet{
    fn bet(&self);
}
trait Test :Bet
    fn test(&self);
}

impl Test for Trade{
    fn test(&self){}
}

impl Trade{
    fn default(&self) -> Vec<Box<dyn Test>>{
        let mut v = Vec::new();
        let trade = Trade(0);
        v.push(Box::new(trade) as Box<dyn Test > );
        v
    }
}

这个是没有问题的。

但是,如果把Test改一下:

trait Test :Send
    fn test(&self);
}

除了Send外,Sync ,Clone,Sized加上去都会报错。
在这里插入图片描述
1、修改 Vec::new => vec![]

#[derive(Clone)]
struct Trade(i32);
trait Bet{
    fn bet(&self);
}
trait Test :Send+Sync
    fn test(&self);
}

impl Test for Trade{
    fn test(&self){}
}

impl Trade{
    fn default(&self) -> Vec<Box<dyn Test>>{
        let mut v = Vec::new();
        let trade = Trade(0);
        v.push(Box::new(trade) as Box<dyn Test > );
        v
    }
}

但是,如果是,Sized、Clone组合,仍会报错。

有人解释,加上Clone不是安全的trait。
即object-safe trait.

2、object-safe trait 问题

trait object 它不仅包括指向真实对象的指针,还包括一个指向虚函数表的指针。因此,并不是所有的trait都能作为trait对象使用的。

只有 对象安全(object safe)的 trait 才可以组成 trait 对象。trait的方法满足以下两条要求才是对象安全的:

(1)返回值类型不为 Self
(2)方法没有任何泛型类型参数

Clone是非对象安全的,所以不能作为trait对象。

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部