如何定义带有参数和 return 类型(如 Fn)的特征?

How can I define a trait with arguments and return types like Fn?

我被下面的代码搞糊涂了(Listing 13-9):

struct Cacher<T>
where
    T: Fn(i32) -> i32,
{
    calculation: T,
    value: Option<i32>,
}

我知道 Fn 是一个特征,但通常特征没有参数和返回类型。如何定义 Fn?

这样的特征

我试着看了at the definition (actually it's FnOnce, but Fn has FnMut bound and FnMut has FnOnce bound...), but I'm still confused. What is the meaning of that <Args>? Then also something written about it in the Nomicon;但我不明白:

Where Fn(a, b, c) -> d is itself just sugar for the unstable real Fn trait

How can I define a trait with arguments and return types like Fn?

如果您指的是语法 MyTrait(A) -> B,则不能。 "arguments" 和 "return types" 的特征是特殊的,仅限于 FnFnMutFnOnce 特征。这是硬编码到编译器中的。甚至还有一条特定的错误消息:

error: parenthetical notation is only stable when used with `Fn`-family traits (see issue #29625)
 --> src/main.rs:5:8
  |
5 |     A: MyTrait(A) -> B,
  |        ^^^^^^^^^^^^^^^

话虽如此,此语法已脱糖为标准特征语法。你可以从文档中看到 FnOnce 是什么:

pub trait FnOnce<Args> {
    type Output;
    extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
}

编译器将Fn(A, B, C) -> Z转换为Fn<(A, B, C), Output = Z>Args 是标准特征泛型类型参数,Output 是标准关联类型。 "rust-call" ABI 是一些内部编译器机制,它使它更高效,并且在大多数情况下可以忽略。

您完全可以使用通用参数和关联类型创建自己的特征。只是不允许您使用括号符号。