V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
wtfedc
V2EX  ›  问与答

请教个 golang 自定义 interface 作 函数形参 的问题

  •  
  •   wtfedc · 2022-12-27 15:06:59 +08:00 · 700 次点击
    这是一个创建于 478 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码如下

    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 就不行。来个朋友指点一下

    7 条回复    2022-12-27 16:19:32 +08:00
    yleoer
        1
    yleoer  
       2022-12-27 15:45:56 +08:00   ❤️ 1
    将 `var courses []Course` 改为 `var courses []ObjForGroupBy`。
    ripperdev
        2
    ripperdev  
       2022-12-27 15:50:06 +08:00   ❤️ 1
    https://gist.github.com/ripperdev/c91babc583caa2f618b67ee7f483b521
    可以用反射实现,不知道大佬们有没有更好的方法
    RoninZc
        3
    RoninZc  
       2022-12-27 16:06:18 +08:00   ❤️ 1
    zsj950618
        4
    zsj950618  
       2022-12-27 16:07:47 +08:00   ❤️ 1
    wtfedc
        5
    wtfedc  
    OP
       2022-12-27 16:10:46 +08:00
    @yleoer 因为要用 Course 结构,来给 courses 灌特定属性的数据,比如{Day:"Monday"},如果 courses 用 ObjForGroupBy 声明,意思就变了,Course 的声明也就多次一举了

    @ripperdev 感谢代码援助,考虑到 reflect 是在运行时判断类型结构,性能一般(虽然用不到高性能,纯属意淫),原想着在编译期就把逻辑固定下来,遇到这么个问题
    wtfedc
        6
    wtfedc  
    OP
       2022-12-27 16:14:48 +08:00
    @yleoer 刚反应过来,一语点醒我梦中人,果然可以
    lysS
        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)
    }

    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3489 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 11:08 · PVG 19:08 · LAX 04:08 · JFK 07:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.