D语言代码:array_column函数实现及编译错误解决
以下D语言代码,
import std.stdio;
import std.algorithm;
T[] array_column(T, U)(T[U][] array, U key)
{
T[] result;
foreach (row; array)
{
if (key in row.keys)
{
result ~= row[key];
}
}
return result;
}
void main()
{
string[string][] one = [ [ 'name':'chenfa', 'age':'33' ], [ 'name':'tanlili', 'age':'44' ] ];
writeln(array_column(one, 'name'));
}
编译出错,请给我纠正下,或者给出您的实现方式
a_array_colums_test.d(9): Error: none of the overloads of template std.algorithm.searching.canFind are callable using argument types !()(string[string], string)
/home/chenfa/dev_soft/dmd_all/usr/include/dmd/phobos/std/algorithm/searching.d(2540): Candidate is: canFind(alias pred = "a == b")
a_array_colums_test.d(22): Error: template instance a_array_colums_test.array_column!(string, string) error instantiating
问题在于 row 是 string[string] 类型,而 canFind 函数的参数类型是 string,所以编译器无法匹配函数调用。可以改为使用 in 关键字来判断 key 是否在 row 的键中出现:
T[] array_column(T, U)(T[U][] array, U key)
{
T[] result;
foreach (row; array)
{
if (key in row.keys)
{
result ~= row[key];
}
}
return result;
}
这里使用 row.keys 来获取 row 的所有键,并使用 in 来判断 key 是否在其中出现。
原文地址: https://www.cveoy.top/t/topic/oidy 著作权归作者所有。请勿转载和采集!