是否可以将闭包作为函数中的可选参数?
我需要这样的东西(伪代码):
fn function(x: int, optional expr |int| -> int) -> int
用法是这样的:
// just the mandatory argument
n = function(z);
或可选:
// passed closure would be called inside the function
n = function(z, |x| x * x);
即使可能的话,我也无法掌握正确的语法(希望使用正确的匹配表达式的完整示例)。
最佳答案
可选参数在 wish list 中,但他们还没有使用该语言,AFAIK。
你显然可以做的是做两个函数
fn function(x: int) -> int {function_with_expr (x, |n|n*n)}
fn function_with_expr(x: int, expr: |int| -> int) -> int
这是标准库中使用的方法。
您还可以将特殊特征传递给函数,例如传递 ToSocketAddr进入bind ,然后您可以为各种元组类型实现该特征。不过,我不确定通过元组传递闭包是否会像直接传递它一样简单。
关于Rust 中作为可选函数参数的闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26914160/