【问题标题】:How to call an associated function on a generic type?如何在泛型类型上调用关联函数?
【发布时间】:2019-02-21 00:12:33
【问题描述】:

我在一个文件中有 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.
    }
}

【问题讨论】:

  • 请查看如何创建minimal reproducible example,然后查看edit 您的问题以包含它。我们无法分辨代码中存在哪些类型、特征、字段等。尝试在Rust Playground 或全新的 Cargo 项目中重现您的错误。有Rust-specific MCVE tips 可以用来减少您在此处发布的原始代码。
  • 来自 Trait 的第二个实现 - 这里只有 一个 Trait 的实现。

标签: rust traits


【解决方案1】:

您需要使用turbofish (::&lt;&gt;) 语法:

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 语法的相关问题:

【讨论】:

  • @WeslyWiser 如果您觉得我的更改与您的实际答案不符,请随时回滚。我只是想提供额外的资源 regatrdint turbofish 语法
猜你喜欢
  • 1970-01-01
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多