Search code examples
gogo-interface

Can I generically specifiy a Method for a Go-Lang Struct?


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

Solution

  • 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