Rust 编译器看不到 Sized 的结构 [英] Rust compiler does not see structure as Sized
问题描述
我试图定义一个特征如下:
I am trying to define a trait as follows:
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>>);
即参数集合是不同类型参数的混合.但是编译会出现以下错误:
That is, the parameter collection is a mixture of parameters of different types. However compiling gives the following error:
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`
我从这篇文章得知Vec
必须是 Sized
,但似乎 Parameter
应该被调整大小(因为 Box
)所以我如何说服 RustParameter
是 Sized
类型的编译器?
I am aware from this post that Vec
must be Sized
, but it seems that Parameter
should be sized (because of the Box
) so how do I convince the Rust compiler that Parameter
is a Sized
type?
推荐答案
Rust 中的类型参数有一个 隐式Sized
绑定,除非另有说明(通过添加?Sized
绑定).
Type parameters in Rust have an implicit Sized
bound unless otherwise specified (by adding a ?Sized
bound).
所以 Parameter
结构声明是有效的:
So the Parameter
struct declaration is effectively:
pub struct Parameter<A: Parameterisable+Sized>(&'static str, Box<A>);
请注意,Parameter
本身总是有大小的,因为 &'static str
和 Box
总是有大小的;边界只是说 T
也必须调整大小.
Note that Parameter<T>
is always itself sized, since &'static str
and Box<A>
are always sized; the bound just says that T
must also be sized.
错误消息支持了这一点;它是说 Parameterisable
不是 Sized
,不是 Parameter
不是 Sized
.
The error message backs this up; it's saying that Parameterisable
is not Sized
, not that Parameter<Parametrerisable>
is not Sized
.
所以正确的更改是添加 ?Sized
绑定:
So the correct change is to add the ?Sized
bound:
pub struct Parameter<A: Parameterisable+?Sized>(&'static str, Box<A>);
这篇关于Rust 编译器看不到 Sized 的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!