代码如下
package main
type ObjForGroupBy interface {
GetValueForGroupBy() string
}
func GroupBy(data []ObjForGroupBy) map[string][]ObjForGroupBy {
var result = make(map[string][]ObjForGroupBy)
for _, obj := range data {
strV := obj.GetValueForGroupBy()
result[strV] = append(result[strV], obj)
}
return result
}
type Course struct {
Day string
}
func (c Course) GetValueForGroupBy() string {
return c.Day
}
func main() {
var courses []Course
courses = append(courses, Course{Day: "Monday"})
GroupBy(courses)
}
报错为
cannot use courses (variable of type []Course) as type []ObjForGroupBy in argument to GroupBy
搞的我有点懵,是我理解错了 interface 吗?传单数 ObjForGroupBy 的函数,可以正常用,传 slice 就不行。来个朋友指点一下
1
yleoer 2022-12-27 15:45:56 +08:00 1
将 `var courses []Course` 改为 `var courses []ObjForGroupBy`。
|
2
ripperdev 2022-12-27 15:50:06 +08:00 1
https://gist.github.com/ripperdev/c91babc583caa2f618b67ee7f483b521
可以用反射实现,不知道大佬们有没有更好的方法 |
3
RoninZc 2022-12-27 16:06:18 +08:00 1
|
4
zsj950618 2022-12-27 16:07:47 +08:00 1
|
5
wtfedc OP |
7
lysS 2022-12-27 16:19:32 +08:00
GroupBy 是方法的单参数就行了
```golang type ObjForGroupBys map[string][]ObjForGroupBy func (o ObjForGroupBys) GroupBy(obj ObjForGroupBy) { strV := obj.GetValueForGroupBy() o[strV] = append(o[strV], obj) } ``` |