Ath*_*ick 0 closures optional-parameters argument-passing optional rust
是否可以将闭包作为函数中的可选参数?
我需要这样的东西(伪代码):
fn function(x: int, optional expr |int| -> int) -> int
Run Code Online (Sandbox Code Playgroud)
和用法将是这样的:
// just the mandatory argument
n = function(z);
Run Code Online (Sandbox Code Playgroud)
或者可选:
// passed closure would be called inside the function
n = function(z, |x| x * x);
Run Code Online (Sandbox Code Playgroud)
如果它甚至可能,我只是无法掌握正确的语法(会欣赏正确匹配表达式的完整示例).
可选参数在愿望清单中,但它们还没有语言,AFAIK.
你显然可以做的是做两个功能
fn function(x: int) -> int {function_with_expr (x, |n|n*n)}
fn function_with_expr(x: int, expr: |int| -> int) -> int
Run Code Online (Sandbox Code Playgroud)
这是标准库中使用的方法.
您还可以将特殊特征传递给函数,例如将ToSocketAddr传递给bind,然后您可以为各种元组类型实现该特征.我不确定是否通过元组传递闭包就像直接传递它一样简单.