【发布时间】:2018-08-13 12:13:09
【问题描述】:
我有以下代码:
trait Bar {
fn baz(&self, arg: impl AsRef<str>)
where
Self: Sized;
}
struct Foo;
impl Bar for Foo {
fn baz(&self, arg: impl AsRef<str>) {}
}
fn main() {
let boxed: Box<dyn Bar> = Box::new(Foo);
boxed.baz();
}
导致此错误的原因:
error: the `baz` method cannot be invoked on a trait object
--> src/main.rs:15:11
|
15 | boxed.baz();
| ^^^
为什么这不可能?当我删除 Self: Sized 绑定时它可以工作,但是我不能使用泛型来使调用者更舒适。
这不是 Why does a generic method inside a trait require trait object to be sized? 的副本,它询问为什么不能从 trait 对象调用 baz。我不是在问为什么需要绑定;这有already been discussed。
【问题讨论】:
标签: rust traits trait-objects