【发布时间】:2015-07-20 11:58:07
【问题描述】:
我知道特征和切片没有大小,即在编译时不可能知道它们的大小,例如任何类型都可以实现特征,但该类型可能没有大小。
但是,这个示例代码不是意味着每个实现了 trait Foo 的类型也需要实现 Sized 吗?
trait Foo: Sized {}
struct Bar(i64);
impl Foo for Bar {}
如果是这样,为什么这不起作用?
impl From<Foo> for Bar {
fn from(foo: Foo) -> Bar {
Bar(64)
}
}
error[E0277]: the trait bound `Foo + 'static: std::marker::Sized` is not satisfied
--> src/main.rs:7:6
|
7 | impl From<Foo> for Bar {
| ^^^^^^^^^ `Foo + 'static` does not have a constant size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `Foo + 'static`
我想为库的使用者提供一个类型(我们将其命名为 Bar)并使其能够从任何其他实现特定特征的类型转换为 Bar(我们将其命名为 Foo) .
我通过通过引用而不是值传递 Foo 来解决它,但我不确定如果实现者需要 Sized,编译器为什么会抱怨。
【问题讨论】:
标签: rust