相关疑难解决方法(0)

为什么在以“Self: Sized”为界时不能调用特征对象上的函数?

我有以下代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

操场

这导致此错误:

error: the `baz` method cannot be invoked on a trait object
  --> src/main.rs:15:11
   |
15 |     boxed.baz();
   |           ^^^
Run Code Online (Sandbox Code Playgroud)

为什么这是不可能的?当我删除Self: Sized绑定时它可以工作,但是我不能使用泛型来使调用者更舒适地使用该函数。

这不是为什么 trait 中的泛型方法需要调整 trait 对象的大小?这问为什么你不能baz从特征对象调用。我不是问为什么需要绑定;这已经讨论过了

traits rust trait-objects

5
推荐指数
1
解决办法
2384
查看次数

标签 统计

rust ×1

trait-objects ×1

traits ×1