【问题标题】:Closures as optional function arguments in Rust闭包作为 Rust 中的可选函数参数
【发布时间】:2014-11-13 16:53:45
【问题描述】:

是否可以将闭包作为函数中的可选参数?

我需要这样的东西(伪代码):

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);

如果可能的话,我只是无法掌握正确的语法(会欣赏带有正确匹配表达式的完整示例)。

【问题讨论】:

    标签: closures rust argument-passing optional-parameters optional


    【解决方案1】:

    可选参数在 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,然后您可以为各种元组类型实现该特征。不过,我不确定通过元组传递闭包是否会像直接传递一样简单。

    【讨论】:

      猜你喜欢
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 2019-11-01
      相关资源
      最近更新 更多