是否有惯用的 Rust 方法来绑定(bind)函数参数并生成新函数?
例如,假设我有以下功能:
fn eq(a: i32) -> Box<Fn(i32) -> bool> {
let target = a; // copy
Box::new(move |value| value == target)
}
fn evaluate(func: Box<Fn(i32) -> bool>, value: i32) -> bool {
func(value)
}
eq
使用的 Box
机制是否是一种将参数绑定(bind)到函数以在 evaluate
中使用的合理方式?例如像这样:
let is_42 = eq(42);
assert_eq!(true, evaluate(is_42, 42));
还有生命周期的问题。我想知道在 eq()
中延长 target
生命周期的正确语义是什么,因此它的生命周期与装箱函数的生命周期绑定(bind)。
最佳答案
Is there an idiomatic Rust way of binding function arguments and producing a new function?
是的,Rust 有闭包,它实际上是函数 + 绑定(bind)环境。
因此,绑定(bind)函数参数或部分应用它只是形成一个闭包的问题,闭包将使用一些固定参数调用此函数。
Is the
Box
mechanism used byeq
a sane way of binding an argument to a function for usage inevaluate
?
目前是。
Rust 闭包的问题在于它们是 Voldemort 类型(即无法命名的类型)。因此,虽然您可以将闭包分配给局部变量,并让推理推导出类型,但实际上您不能从函数1 中返回它。
目前,解决方法是返回 -> Box<Fn(..) -> ..>
在这种情况下。
但是,您的签名evaluate
是不必要的约束。而不是服用 Box
,你可以引用一下:
fn evaluate(f: &Fn(i32) -> bool, value: i32) -> bool { f(value) }
这将使可以调用 evaluate
的用户直接释放 NOT 在堆上分配(Box
会这样做)。
1 允许将返回类型指定为 -> impl SomeTrait
的工作正在进行中这将允许您这样做。
There's also the issue of lifetimes. I'm wondering what the correct semantics would be for extending the lifetime of
target
ineq()
, so its lifetime is bound to the lifetime of the boxed function.
不可能延长生命周期;生命周期是描述性的,而不是规定性的:它只是表示实际生命周期的符号,而不是指定值应具有的生命周期的方法。
对于闭包,您可能需要 move
他们在闭包内的环境;采取按值(value)而不是引用来捕捉。它应该可以解决大多数生命周期问题。
对于剩余的生命周期问题,您实际上采取了另一种方式,通过表示其环境的生命周期来限制闭包的类型:F: Fn(i32) -> bool + 'a
标记F
仅对 'a
有效.
关于rust - 绑定(bind)函数参数和传递绑定(bind)函数的惯用方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43029026/