2

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
    You can't, but you could use embedding, so that embedding a mypkg.ID in any struct gives it the IDHexString method. Sadly I don't have time to write up details, but golang.org/doc/effective_go.html#embedding may help. Commented Sep 29, 2014 at 19:30

2 Answers 2

4

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 { ... } 
Sign up to request clarification or add additional context in comments.

Comments

3

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.