如何在泛型类型上调用关联函数?
How to call an associated function on a generic type?
我在一个文件中有 2 个特征实现。如何从 Trait
的第二个实现中调用 first_function
?
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.
}
}
您需要使用 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();
}
}
另请参阅有关 turbofish 语法的相关问题:
我在一个文件中有 2 个特征实现。如何从 Trait
的第二个实现中调用 first_function
?
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.
}
}
您需要使用 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();
}
}
另请参阅有关 turbofish 语法的相关问题: