【发布时间】:2016-07-17 23:50:47
【问题描述】:
为什么这两个有效:
fn apply_once1<F: FnOnce(T1) -> T2, T1, T2> (f: F, x: T1) -> T2 {
f(x)
}
fn apply_once2<F, T1, T2> (f: F, x: T1) -> T2
where F: FnOnce(T1) -> T2
{
f(x)
}
但是这个不能编译:
fn apply_once3<T1, T2> (f: FnOnce(T1) -> T2, x: T1) -> T2 {
f(x)
}
它抱怨:
error: the trait `core::marker::Sized` is not implemented for the type `core::ops::FnOnce(T1) -> T2 + 'static` [E0277]
once3<T1, T2> (f: FnOnce(T1) -> T2, x: T1) -> T2 {
^
help: see the detailed explanation for E0277
note: `core::ops::FnOnce(T1) -> T2 + 'static` does not have a constant size known at compile-time
note: all local variables must have a statically known size
我知道FnOnce 可能没有静态已知的大小,所以通常我会用& 将变量交换为引用来解决这个问题,所以现在知道大小了。但我不明白为什么apply_once1 和apply_once2 能侥幸逃脱?
四处搜索,我找不到任何关于将特征绑定在参数上与将其放在类型变量上之间的区别的任何内容。
【问题讨论】:
标签: closures rust higher-order-functions