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

问题描述 投票:0回答:1

我在一个文件中有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.
    }
}
rust traits
1个回答
1
投票

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

Module::<T>::first_function()

完整的例子:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.