Why can't we make a trait with non-method associated functions into a trait object?

Viewed 88

According to the explanation, Rust rejects to make a trait with non-method associated functions into a trait object.

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

Why can't we just put the address of the non-method associated function into the vtable, thus we can call it through the vtable and make the trait into a trait object too. It seems that there aren't any obstacles to dealing it this way.

I'd think this is a more elegant approach to cope with these traits rather than simply excluding them from making trait objects.

1 Answers

To get a vtable, you need an instance of the object. At this point, you already have an instance, so there is little advantage to not having the method taking &self.

It can have by not requiring static dispatch to have an instance; but this is a very minor thing, and nobody has even bothered to write an RFC for that. Not to mention that the syntax will need to be decided.

Related