以下是一个实现该功能的 Go 程序:

package main

import (
    "fmt"
    "reflect"
)

func groupBy(arr interface{}, keyname string) map[interface{}][]interface{} {
    result := make(map[interface{}][]interface{})
    arrValue := reflect.ValueOf(arr)

    for i := 0; i < arrValue.Len(); i++ {
        item := arrValue.Index(i)
        key := item.FieldByName(keyname).Interface()
        result[key] = append(result[key], item.Interface())
    }

    return result
}

func main() {
    type Person struct {
        Name string
        Age  int
    }

    people := []Person{
        {'Alice', 25},
        {'Bob', 30},
        {'Charlie', 25},
    }

    result := groupBy(people, 'Age')

    fmt.Println(result)
}

该程序使用了反射机制,可以接受任何类型的数组作为输入,并根据指定字段进行分组。在上面的示例中,我们定义了一个 Person 结构体,并使用该结构体的 Age 字段进行分组。程序输出如下:

map[25:[{'Alice' 25} {'Charlie' 25}] 30:[{'Bob' 30}]]

可以看到,程序成功按照 Age 字段将 Person 数组分成了两组,并输出了一个 map。

Golang 实现数组分组:根据指定字段将数组分类

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

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