简体   繁体   English

如何返回一个函数?

[英]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. 因此,每当您有一个捕获外部变量的闭包(捕获fg )时,它就被链接到创建它的堆栈框架。

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.

相关问题 如何更改此功能的返回类型? - How can I change the return type of this function? 如何从函数返回JoinHandle? - How can I return a JoinHandle from a function? 如何从 Rust 中的成员 function 返回泛型类型 - How can I return a generic type from a member function in Rust Rust - 如何返回不同 function 的错误? - Rust - how can I return error of a different function? 如果没有要返回的内容,如何从泛型函数返回有意义的东西? - How can I return something meaningful from a generic function if there is nothing to return? Rust - 如何从函数返回多个变量,以便在调用函数的范围之外可以访问它们? - Rust - How can I return multiple variables from a function such that they are accessible outside the scope the function is called in? 如何定义可以返回给定 integer 类型的通用 function ? - How can I define a generic function that can return a given integer type? 如何在类似函数的过程宏中计算类型的实例并返回它? - How can I compute an instance of a type in a function-like procedural macro and return it? A Rust function 返回一个future,after.await(),可能会引发恐慌。? 我怎样才能避免恐慌! 停止程序? - A Rust function return a future, after .await(), it may be throw a panic!. How can I avoid the panic! to stop the program? 如何根据作为参数传递的闭包的返回类型来更改 function 的行为? - How can I alter the behavior of a function based on the return type of a closure passed as an argument?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM