4

I am reading Object Safety Is Required for Trait Objects and I don't understand the problem with generic type parameters.

The same is true of generic type parameters that are filled in with concrete type parameters when the trait is used: the concrete types become part of the type that implements the trait. When the type is forgotten through the use of a trait object, there is no way to know what types to fill in the generic type parameters with.

I am trying to code an example but I can't make sense of it. Generic type parameters for what?

I tried to make a trait object out of a parameterized trait, but once the parameter is given a concrete value it works just fine:

trait Creator<T> {
    fn create(&self) -> T;
}

struct CreationHouse {
    creators: Vec<Box<dyn Creator<u32>>>
}

struct NumCreator { seed: u32 }

impl Creator<u32> for NumCreator {
    fn create(&self) -> u32 {
        return self.seed;
    }
}

fn main() {
    let ch = CreationHouse{
        creators: vec![Box::new(NumCreator{seed: 3})]
    };
}

(Compiles well, except "unused" warnings)

What I don't get is what does it mean "generic type parameters that are filled in with concrete type parameters when the trait is used" and how could the generic types be lost (as the trait "carries" them with itself). If you could write an example of the case described in the paragraph I'd be grateful.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Neo
  • 3,534
  • 2
  • 20
  • 32

2 Answers2

6

what does it mean "generic type parameters that are filled in with concrete type parameters when the trait is used"

An example that won't work is when the type parameter is part of a method:

trait Foo {
    fn foo<T>(t: T) {}
}

When a function has a type parameter, Rust will monomorphize the function (make a new copy) for each type that it is actually called with. This isn't compatible with trait objects because Rust doesn't know which impl the method belongs to until runtime.

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
  • I think I agree the original paragraph is fairly confusing. Maybe someone should send a PR? – Lukas Kalbertodt Jul 29 '19 at 11:35
  • Can I say the problem is that the compiler can't trace all the calls to `foo` (as the dispatch is dynamic) and so it can't know which T types it should monomorphize `foo` for? I'm not sure I understand what is the "caller of `foo`". – Neo Jul 29 '19 at 12:04
  • Because as far as I understand, the specific implementation for a specific function call is available in runtime (via the lookup table) which should be enough, except for generics it isn't - as the code should be monomorphized which happens compile time (?). – Neo Jul 29 '19 at 12:17
  • @Neo I changed the last paragraph to hopefully clear that up. – Peter Hall Jul 29 '19 at 14:03
6

As @PeterHall mentioned, with a generic method the trait cannot be object-safe.

The reason, it turns out, is simply an implementation limitation.

Efficient dispatch to the correct implementation of a trait method is achieved by using a virtual-table, which is essentially a table of pointer-to-functions. Each method in the trait object gets one slot in the virtual-table to store one pointer-to-function.

On the other hand, a generic function or method is no function or method at all. It's a blueprint to create as many different functions or methods as one wishes by substituting the generic parameters with actual, concrete, parameters.

This means that it is not possible to have a pointer-to-function for fn foo<T>() -> T; as there is no code for it, instead you may have a pointer-to-function for one fn foo<i32>() -> i32, and another pointer-to-function for one fn foo<String>() -> String, and another...

The impossibility to have a pointer-to-function, and thus a v-table entry, for a generic method makes it impossible to call that method via run-time dispatch, that is, on a dyn Trait.

It is notable that other languages also suffer the same restriction, for the same reasons; C++ cannot have template virtual methods either, for example.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
  • 1
    *simply an implementation limitation* — this makes it seem like with the right pull request, Rust could support it, but I don't believe that's the case. Maybe you could clarify how the limitation could be lifted? – Shepmaster Jul 29 '19 at 15:08
  • 2
    @Shepmaster: I was wondering if I should. Whole Program Analysis would allow obtaining the set of instantiations of `foo` and create a pointer-to-function for each; forever precluding DLLs. HashMaps keyed on TypeId would allow fully dynamic look-up, at the cost of increased look-up times. It is a solvable problem, but the "solutions" have costs of their own. – Matthieu M. Jul 29 '19 at 15:27
  • 2
    C++ does not even need this because C++ has inheritance. Task:- define an API that has a call put(&self, k:&dyn Serialize, v:&dyn Serialize) - not possible in rust. In C++, you would do abstract class API {virtual void put(Serialize k, Serialize v); }. There is no way to do the equivalent thing in rust. Quite lacking in my opinion. Anyone implementing the API must implement that method. How do you do the same in rust? Or is there no way to create this API definition? – user2833557 Aug 07 '20 at 15:55