[英]How can I return a function?
I tried recreate functional composition 我尝试重新创建功能组合
fn compose<A, B, C>(f : |B| -> C,
g : |A| -> B)
-> |A| -> C{
|x| f(g(x))
}
But I get a lifetime error. 但是我收到一生的错误。 I read that closures are stack based but it doesn't explain why I get this error.
我读到闭包是基于堆栈的,但没有解释为什么我会收到此错误。
let f3 = compose(f1,f2);
Can't I move the closure out of it's current scope? 我不能将闭包移出当前范围吗?
Yes, Rust's current closures capture by reference, and place the closure's environment (ie the references to the captured variables) on the stack, referring to it via a reference. 是的,Rust的当前闭包通过引用捕获,并将闭包的环境(即对捕获变量的引用)放置在堆栈上,通过引用对其进行引用。 Hence, any time you have a closure that captures outer variables (you are capturing
f
and g
), it is chained to the stack frame in which it was created. 因此,每当您有一个捕获外部变量的闭包(捕获
f
和g
)时,它就被链接到创建它的堆栈框架。
C++11-style unboxed closures solve this, by allowing values to be captured by value, and allowing the environment to be stored directly (ie no compulsory references). C ++ 11样式的无盒装闭包通过允许按值捕获值并允许直接存储环境(即没有强制引用)来解决此问题。 The exact syntax is yet to be finalised, but what you wrote may be valid.
确切的语法尚未确定,但是您写的内容可能是有效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.