作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
是否可以将闭包作为函数中的可选参数?
我需要这样的东西(伪代码):
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/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!