gpt4 book ai didi

go - 我通常可以为 Golang 结构指定方法吗?

转载 作者:IT王子 更新时间:2023-10-29 01:22:23 25 4
gpt4 key购买 nike

我一直在阅读 the go-lang interface doc ;但是我仍然不清楚是否有可能实现我想要的

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()
}

这会很好用;但是我更喜欢一些惯用的方法来将通用方法应用于两种类型并且只定义一次。类似的东西:

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()
}

最佳答案

本质上你不能像你习惯的那样,但你可以做的是匿名继承一个 super 结构(抱歉,这不是合法的词:P):

type A struct {

}

type B struct {
A // Anonymous
}

func (A a) IDHexString() string {

}

B 现在将能够实现 IDHexString 方法。

这就像在许多其他语言中一样:

class B extends A { ... }

关于go - 我通常可以为 Golang 结构指定方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26107358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com