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()
}
SMTF
  • 705
  • 10
  • 16
  • 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 http://golang.org/doc/effective_go.html#embedding may help. – twotwotwo Sep 29 '14 at 19:30

2 Answers2

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 { ... }
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
peterSO
  • 158,998
  • 31
  • 281
  • 276