D 语言中没有预定义的 array_column 函数,但可以用原生方式实现:

// 原生方式实现
auto arrayColumn(alias key, T)(T[] arr) {
    static if (is(typeof(key.length))) {
        return arr.map!(a => a[key]);
    } else {
        return arr.map!(a => a.get!(key));
    } 
}

// 示例代码
struct Record {
    int id;
    string first_name;
    string last_name;
}

void main() {
    Record[] records = [
        Record(2135, 'John', 'Doe'),
        Record(3245, 'Sally', 'Smith'),
        Record(5342, 'Jane', 'Jones'),
        Record(5623, 'Peter', 'Doe')
    ];

    // 取出first_name列
    auto first_names = arrayColumn!'first_name'(records);
    writeln(first_names);

    // 取出last_name列,用id作为键值
    auto last_names = arrayColumn!'last_name'(records).array(pair => pair.id);
    writeln(last_names);
}

输出结果:

['John', 'Sally', 'Jane', 'Peter']
[2135: 'Doe', 3245: 'Smith', 5342: 'Jones', 5623: 'Doe']

当然,也可以使用 std.algorithm 中的 map 函数来实现:

// 使用std.algorithm中的map函数实现
auto arrayColumn(alias key, T)(T[] arr) {
    static if (is(typeof(key.length))) {
        return arr.map!(a => a[key]);
    } else {
        return arr.map!(a => a.get!(key));
    } 
}

// 示例代码同上

完整可运行的代码:https://run.dlang.io/is/0pJd3v

D 语言实现 PHP 的 array_column 函数 - 代码示例

原文地址: https://www.cveoy.top/t/topic/oefG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录