我试图将一个特质定义如下:
pub struct Parameter<A: Parameterisable>(&'static str, Box<A>);
pub trait Parameterisable {
// Some functions
}
impl Parameterisable for i32 {}
impl Parameterisable for f64 {}
pub struct ParameterCollection(Vec<Parameter<Parameterisable>>);
也就是说,参数集合是不同类型参数的混合体。但是编译出现以下错误:
error[E0277]: the trait bound `Parameterisable + 'static: std::marker::Sized` is not satisfied
--> src/main.rs:10:32
|
10 | pub struct ParameterCollection(Vec<Parameter<Parameterisable>>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ trait `Parameterisable + 'static: std::marker::Sized` not satisfied
|
= note: `Parameterisable + 'static` does not have a constant size known at compile-time
= note: required by `Parameter`
我知道从这个帖子 https://stackoverflow.com/questions/25818082/vector-of-objects-belonging-to-a-trait that Vec
必须是Sized
,但似乎Parameter
应该调整大小(因为Box
)那么我如何说服 Rust 编译器Parameter
is a Sized
type?
Rust 中的类型参数有一个隐含的Sized bound http://huonw.github.io/blog/2015/01/the-sized-trait/除非另有说明(通过添加?Sized
bound).
So the Parameter
结构声明实际上是:
pub struct Parameter<A: Parameterisable+Sized>(&'static str, Box<A>);
注意Parameter<T>
总是自身大小,因为&'static str
and Box<A>
总是有尺寸的;界限只是说T
还必须确定尺寸。
错误消息支持了这一点;它是这么说的Parameterisable
is not Sized
, 不是那个Parameter<Parametrerisable>
is not Sized
.
所以正确的改变是添加?Sized
bound:
pub struct Parameter<A: Parameterisable+?Sized>(&'static str, Box<A>);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)