dtfbj24048 2014-09-29 19:26
浏览 7
已采纳

我可以遗传地指定Golang结构的方法吗?

I have been reading over the go-lang interface doc ; however it is still not clear to me if it is possible to achieve what I'd like

type A struct {
    ID SomeSpecialType
}

type B struct {
    ID SomeSpecialType
}

func (a A) IDHexString() string {
    return a.ID.Hex()
}

func (b B) IDHexString() string {
    return b.ID.Hex()
}

This will work fine; however I'd prefer some idiomatic way to apply the common method to both types and only define it once. Something Like:

type A struct {
    ID SomeSpecialType
}

type B struct {
    ID SomeSpecialType
}

func (SPECIFY_TYPE_A_AND_B_HERE) IDHexString() string {
    return A_or_B.ID.Hex()
}
  • 写回答

2条回答 默认 最新

  • dongwuqi4243 2014-09-29 20:34
    关注

    For example, using composition,

    package main
    
    import "fmt"
    
    type ID struct{}
    
    func (id ID) Hex() string { return "ID.Hex" }
    
    func (id ID) IDHexString() string {
        return id.Hex()
    }
    
    type A struct {
        ID
    }
    
    type B struct {
        ID
    }
    
    func main() {
        var (
            a A
            b B
        )
        fmt.Println(a.IDHexString())
        fmt.Println(b.IDHexString())
    }
    

    Output:

    ID.Hex
    ID.Hex
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)