Kalanamith
Kalanamith

Reputation: 20648

How to call an associated function on a generic type?

I have 2 trait implementations in a file. How can I call the first_function from the second implementation of Trait?

impl<T: Trait> Module<T> {
    pub fn first_function() {
        // some code here
    }
}

impl<T: Trait> Second<T::SomeType> for Module<T> {
    pub fn second_function() {
        // Needs to call the first function available in first trait implementation.
    }
}

Upvotes: 5

Views: 3564

Answers (1)

Wesley Wiser
Wesley Wiser

Reputation: 9851

You need to use turbofish (::<>) syntax:

Module::<T>::first_function()

complete example:

struct Module<T> {
    i: T,
}

trait Trait {
    type SomeType;
}

trait Second<T> {
    fn second_function();
}

impl<T: Trait> Module<T> {
    fn first_function() {
        // some code here
    }
}

impl<T: Trait> Second<T::SomeType> for Module<T> {
    fn second_function() {
        Module::<T>::first_function();
    }
}

Playground

Also see this related question about the turbofish syntax:

Upvotes: 7

Related Questions