Home > Mobile >  "cannot infer type for parameter" How to 'tell' the compiler the type I'm u
"cannot infer type for parameter" How to 'tell' the compiler the type I'm u

Time:08-07

I'm having a compiler error here :

pub fn add_component_to<C: Component<C>>(&mut self, to_entity: u64) {
    self.components.add_component_to(to_entity);
                    ^^^^^^^^^^^^^^^^
    // cannot infer type for type parameter `C` declared on the associated function 
}

this method is a wrapper to call the same method on the components which is a private field.

This is the other add_component_to method:

   pub fn add_component_to<C: Component<C>   'static>(mut self, entity: u64) {
        if !self.components.contains_key(&C::id()) {
            // add a new component array
            self.components.insert(C::id(), Box::new(ComponentArray::<C>::new()));
        }
        // add the component at the entity id in the component array
        match self.components.get_mut(&C::id()) {
            None => println!("Unable to add component : component array was not created !"),
            Some(c_arr) => c_arr.add_component_to(entity),
        }
    }

How to tell the compiler that I want to call the method with the same parameter C ?

For static functions, we can use MyStruct::<C>::my_function()

There has to be a way to simply 'tell' the compiler to use this specific type for this call right ?

CodePudding user response:

You can always use the turbofish (::<_>) to tell Rust about the type arguments in a function call:

pub fn add_component_to<C: Component<C>>(&mut self, to_entity: u64) {
    self.components.add_component_to::<C>(to_entity);
    //                              ^^^^^
    // use the turbofish to tell Rust to use C as the type argument
}
  • Related