我有从模块hello导出的greet命令。我还定义了使用main命令的hello命令。休息参数应该从main传递给hello。
我期待hello命令$values在运行./file.nu one two时遵循,
╭───┬─────────╮
│ 0 │ one │
│ 1 │ two │
╰───┴─────────╯但实际价值是
╭───┬────────────────╮
│ 0 │ [list 2 items] │
╰───┴────────────────╯#!/usr/bin/env nu
module greet {
export def hello [...values: string] {
echo $values
$values | each { $"Hello ($in)" }
}
}
def main [...names: string] {
use greet hello;
echo (hello $names) | length
}如何在传递到$names命令之前销毁hello?
发布于 2022-08-24 15:09:37
只要Nu中还没有列表扩展器操作符(正如@don_安曼在注释中提到的那样),就应该设计带有rest参数的函数,以便能够处理以下两种操作:
选项1:尝试自动检测情况.这里可能有角落的案子,但也许没有。
例如,以下greet可以正确地处理以下两种方法之一:
[one two three] (main的rest参数),然后在greet内部进行非结构化。four five six,它只是作为rest参数传递给greet#!/usr/bin/env nu
module greet {
export def hello [...values: string] {
let values = if (($values | length) == 1) and (($values.0 | describe | str substring ',5') == "list<") {
$values.0
} else {
$values
}
$values | each { $"Hello ($in)" }
}
}
def main [...names: string] {
use greet hello;
hello $names
(hello $names) | length
hello four five six
}> ./greet.nu one two three
╭───┬─────────────╮
│ 0 │ Hello one │
│ 1 │ Hello two │
│ 2 │ Hello three │
╰───┴─────────────╯
3
╭───┬────────────╮
│ 0 │ Hello four │
│ 1 │ Hello five │
│ 2 │ Hello six │
╰───┴────────────╯选项2:作为另一种选择,您可以显式地告诉greet什么时候去变形,什么时候不使用标志:
#!/usr/bin/env nu
module greet {
export def hello [
--destruct
...values: string
] {
let values = if $destruct {
$values.0
} else {
$values
}
$values | each { $"Hello ($in)" }
}
}
def main [...names: string] {
use greet hello;
hello $names
(hello $names) | length
hello --destruct $names
(hello --destruct $names) | length
hello four five six
}./greet.nu one two three
╭───┬─────────────────────────╮
│ 0 │ Hello [one, two, three] │
╰───┴─────────────────────────╯
1
╭───┬─────────────╮
│ 0 │ Hello one │
│ 1 │ Hello two │
│ 2 │ Hello three │
╰───┴─────────────╯
3
╭───┬────────────╮
│ 0 │ Hello four │
│ 1 │ Hello five │
│ 2 │ Hello six │
╰───┴────────────╯https://unix.stackexchange.com/questions/714643
复制相似问题