1

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.

Tim
  • 99
  • 1
  • 5
  • 1
    Given a `bar: Box`, how would you want to call `foo()` for `bar`? `bar.foo()` seems wrong, since it passes `bar` as the `self` parameter, but `foo()` doesn't take one. – Sven Marnach Sep 19 '22 at 08:48

1 Answers1

1

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.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
  • Sorry, I am still confused about it. I'd think if we put the address of the non-method function into the vtable, wouldn't it be more a unified way to make a trait object? Since in this way, we needn't to reject a trait with non-method functions into a trait object. – Tim Sep 19 '22 at 08:27
  • If you control the trait yourself, adding `&self` to an associated function is a minor issue, but less so if you are using a trait from a library. – Sven Marnach Sep 19 '22 at 08:43
  • @SvenMarnach If you think that's important, you're welcome to send an RFC :) – Chayim Friedman Sep 19 '22 at 08:57
  • I don't have a use case for this. I'm just saying that it seems plausible someone else has. – Sven Marnach Sep 19 '22 at 09:06