英文:
Can I generically specifiy a Method for a Go-Lang Struct?
问题
我已经阅读了go-lang接口文档,但我仍然不清楚是否可以实现我想要的功能。
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()
}
英文:
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()
}
答案1
得分: 4
基本上,你不能像你习惯的那样使用"like",但你可以匿名继承一个超结构体(抱歉,这不是合法的词:P):
type A struct {
}
type B struct {
A // 匿名
}
func (A a) IDHexString() string {
}
现在,B
将能够实现IDHexString
方法。
这在许多其他语言中类似于:
class B extends A { ... }
英文:
Essentialy you can't like you're used to, but what you can do is anonymously inherit a super-struct (sorry it's not the legal word :P):
type A struct {
}
type B struct {
A // Anonymous
}
func (A a) IDHexString() string {
}
B
will now be able to implement the IDHexString
method.
This is like in many other languages kind of the same as:
class B extends A { ... }
答案2
得分: 3
例如,使用组合:
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())
}
输出:
ID.Hex
ID.Hex
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论