问题描述
假设我想声明一个函数,其参数是一个字符串数组:
Say I want to declare a function whose parameter is an array of strings:
sub process-string-array(Str[] stringArray) # invalid
{
...
}
我该怎么做?
推荐答案
这取决于您要使用的印记:
It depends on the sigil you want to use:
sub process-string-array(Str @array) { ... } # @-sigil
sub process-string-array(Array[Str] $array) { ... } # $-sigil
请注意,您必须小心传入已声明的 Str 数组才能执行此操作,这意味着临时数组需要使用类型化声明传入:
Note that you have to be careful to pass in a declared Str array to do this which means adhoc arrays will need to passed in with a typed declaration:
my Str @typed-array = <a b c>;
process-string-array <a b c>; # errors
process-string-array @typed-array; # typed array in
process-string-array Array[Str].new: <a b c>; # adhoc typed array
如果你不想处理这样的类型数组,你可以使用 where
子句来接受任何 Any
类型的数组,它碰巧只包含 Str
元素(通常更容易使用 IME):
If you don't want to deal with typing arrays like this, you can use a where
clause to accept any Any
-typed array that happens to include only Str
elements (which is often easier to use IME):
sub process-string-array(@array where .all ~~ Str) { ... }
然而,这(正如 jnthn 在评论中提醒的那样)需要对每个元素进行类型检查(所以 O(n) perf 与 O(1) ),所以根据性能敏感的事情,它可能值得额外的代码噪音.根据 Brad 的建议,您可以 multi
它,以在键入数组时加快速度,并在不键入时回退到较慢的方法.
This, however, (as jnthn reminds in the comments) requires type checking each element (so O(n) perf versus O(1) ), so depending on how performance sensitive things are, it may be worth the extra code noise. Per Brad's suggestion, you could multi
it, to speed things up when the array is typed and fallback to the slower method when not.
multi sub process-string-array(Int @array) {
... # actual processing here
}
multi sub process-string-array(@array where .all ~~ Str) {
process-string-array Array[Int].new: @array
}
这篇关于如何声明一个接受类型化数组参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!