如何检查混合类型参数是否是 HackLang 中的整数向量?
How to check if a mixed type argument is a vector of integers in HackLang?
以下功能并非真实,仅供演示:
function acceptHackArray(mixed $x):someType {
....
// Need to check is $x is a vector of integers
$tmp = '$x is vector<int>';
...
return something;
}
看看 the type-assert library built by HHVM devs, in particular the VectorSpec implementation. At the time of writing, for primitives especially it's nothing too magical, first checking the container type is Traversable, then iterating over the array and asserting the contents into the desired type. You could snip just the relevant bit, using is
on generic types for >= 3.28(如果您不介意的话,旧版本 is_vec
vec
):
function acceptHackArray(mixed $x): someType {
invariant($x is Traversable<_>, '$x is not Traversable');
$tmp = vec[];
foreach($x as $v) {
invariant($v is int, '$v is not int');
$tmp[] = $v;
}
// $tmp is now vec<int>
// ...
}
以下功能并非真实,仅供演示:
function acceptHackArray(mixed $x):someType {
....
// Need to check is $x is a vector of integers
$tmp = '$x is vector<int>';
...
return something;
}
看看 the type-assert library built by HHVM devs, in particular the VectorSpec implementation. At the time of writing, for primitives especially it's nothing too magical, first checking the container type is Traversable, then iterating over the array and asserting the contents into the desired type. You could snip just the relevant bit, using is
on generic types for >= 3.28(如果您不介意的话,旧版本 is_vec
vec
):
function acceptHackArray(mixed $x): someType {
invariant($x is Traversable<_>, '$x is not Traversable');
$tmp = vec[];
foreach($x as $v) {
invariant($v is int, '$v is not int');
$tmp[] = $v;
}
// $tmp is now vec<int>
// ...
}