[英]Vector of traits bounded by Sized
I am trying to see if there is any way to implement a vector of sized traits.我正在尝试查看是否有任何方法可以实现大小特征向量。 I know about trait objects, and using
Vec<Box<dyn traitName>>
if traitName
is ?Sized
.我知道特征对象,如果
traitName
是?Sized
,则使用Vec<Box<dyn traitName>>
。 But what if I have ( https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=43d9ee07cfe643d32a00963aa066c929 ):但是如果我有( https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=43d9ee07cfe643d32a00963aa066c929 ):
trait A: Sized {}
struct B {
c: u64,
}
impl A for B {}
fn lol() -> Vec<A> {
let mut a: Vec<A> = Vec::new();
let b = B { c: 2} ;
a.push(b);
a
}
The error I get is我得到的错误是
8 | fn lol() -> Vec<A> {
| ^
|
help: add `dyn` keyword before this trait
but to fix that I have to use trait objects, which is not possible since A: Sized
.但要解决这个问题,我必须使用特征对象,因为
A: Sized
是不可能的。 Any way to fix this or is it impossible?有什么办法可以解决这个问题还是不可能?
A
where A
is a trait is just an old syntax (forbidden in the 2021 edition) to dyn A
. A
其中A
是一个特征只是dyn A
的旧语法(在 2021 版中被禁止)。 You can't create A
or dyn A
if A: Sized
, ever.如果
A: Sized
永远无法创建A
或dyn A
if you'll run this with the 2018 edition, you'll get errors "the size for values of type (dyn A + 'static)
cannot be known at compilation time" .如果您将在 2018 版中运行它, 您将收到错误“在编译时无法知道类型值的大小
(dyn A + 'static)
” 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.