Trait with associated constants and functions can not be dispatched

Hi guys, I found out that in the trait, if you have any associated constants and functions, it can not be dispatched as dyn trait, can anybody tell me why? thanks

What would this call?

trait MyTrait {
    fn foo();
}

fn main() {
    <dyn MyTrait>::foo();
}

And similar concerns for constants. Note also that this does work today:

fn generic<T: MyTrait + ?Sized>() {
    T::foo()
}

If MyTrait was suddenly object safe, you'd immediately hit the same situation.


For associated functions, you can add a &self parameter and just not use it, or you can add a where Self: Sized bound and have it unavailable for the dyn object.

For associated constants, I'm not sure what the best approach is. Maybe a method

    fn const_thing(&self) -> &'static Thing;

Hi thanks for replying, I wanna know why that trait with constants is non-object safe, would you mind explaining it to me?

The same reason as above:

trait MyTrait {
    const FOO: i32;
}

fn main() {
    let _ = <dyn MyTrait>::FOO; // what is the value here?
}

Accessing a "constant" when you know the type only dynamically loses some usecases for that constant, since you never know its value statically.

In theory the constant can be stored as part of the type's "vtable" or something like that, but then you wouldn't be able to use it, for example, as an array size. (as it is required to be known at compile-time)

I think that the reason that this forbids object safety is for consistency's sake, because otherwise you'd have traits where only some of their items are available through a trait-object, which is (IMO) confusing.

IIRC not too long ago someone suggested loosening this restriction but I can't find an RFC?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.