根据explanation ,Rust 拒绝将具有非方法关联函数的特征放入特征对象中。
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; }
为什么我们不能直接将非方法关联函数的地址放入vtable中,这样我们就可以通过vtable调用它,并将trait也变成trait对象。看来这样处理没有任何障碍。
我认为这是处理这些特征的更优雅的方法,而不是简单地将它们排除在创建特征对象之外。
最佳答案
要获取 vtable,您需要该对象的实例。此时,您已经有了一个实例,因此不使用采用 &self
的方法几乎没有什么优势。
它可以通过不需要静态调度来拥有实例;但这是一件非常小的事情,甚至没有人费心为此编写 RFC。更不用说需要确定语法了。
关于rust - 为什么我们不能将具有非方法关联函数的特征放入特征对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73770232/