Rust compiler does not see structure as Sized

2019-04-14 03:26发布

问题:

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`

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?

回答1:

Type parameters in Rust have an implicit Sized bound unless otherwise specified (by adding a ?Sized bound).

So the Parameter struct declaration is effectively:

pub struct Parameter<A: Parameterisable+Sized>(&'static str, Box<A>);

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.

The error message backs this up; it's saying that Parameterisable is not Sized, not that Parameter<Parametrerisable> is not Sized.

So the correct change is to add the ?Sized bound:

pub struct Parameter<A: Parameterisable+?Sized>(&'static str, Box<A>);


标签: rust