为什么当以`Self:Sized`为界时,不能调用特征对象上的函数?

问题描述 投票:4回答:2

我有以下代码:

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();
}

playground

导致此错误的原因:

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?的副本,它询问为什么不能从特征对象调用baz。我不是在问为什么需要这个界限。这有already been discussed

rust traits trait-objects
2个回答
3
投票

因为Rust的泛型系统通过单态化工作。


0
投票

界限使方法不安全。不是对象安全的特征不能用作类型。

© www.soinside.com 2019 - 2024. All rights reserved.