如何在泛型类型上调用关联函数?

co2*_*f2e 2 traits rust

我在一个文件中有 2 个特征实现。我如何first_function从第二个实现中调用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.
    }
}
Run Code Online (Sandbox Code Playgroud)

Wes*_*ser 5

您需要使用turbofish( ::<>)语法:

Module::<T>::first_function()
Run Code Online (Sandbox Code Playgroud)

完整的例子:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

操场

另请参阅有关 Turbofish 语法的相关问题: