这段代码给我一个编译错误:
trait IBoo {
fn new() -> Box<IBoo>;
}
虽然这段代码编译没有任何错误:
trait IBoo {
//fn new() -> Box<IBoo>;
}
trait IFoo {
fn new() -> Box<IBoo>;
}
- 为什么第一个不编译?
rustc --explain E0038
没有直接提示我为什么不可能。 - 是否可以将构造和方法组合在一个接口(interface)(特征)中?
最佳答案
这是来自 description of E0038 :
Method has no receiver
Methods that do not take a
self
parameter can't be called since there won't be a way to get a pointer to the method table for them.trait Foo { fn foo() -> u8; }
This could be called as
<Foo as Foo>::foo()
, which would not be able to pick an implementation.Adding a
Self: Sized
bound to these methods will generally make this compile.trait Foo { fn foo() -> u8 where Self: Sized; }
你可以这样做:
trait IBoo {
fn new() -> Box<IBoo>
where
Self: Sized;
}
在其他情况下,您可以对整个 impl 进行限制:
关于rust - 为什么特质不能 self 构建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38159771/