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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I think I agree the original paragraph is fairly confusing. Maybe someone should send a PR?
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".
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 I changed the last paragraph to hopefully clear that up.
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.

3 Comments

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: 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.
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.