Same method on different types in Go

I’ve seen some similar questions (http://stackoverflow.com/questions/31505587/how-can-two-different-types-implement-the-same-method-in-golang-using-interfaces), but in my case my types do not have the same base type. My types are arrays of different sizes.

type Ten [10]byte
type Twenty [20]byte

func (t *Ten) GetByte0() byte {
    return t[0]
}

func (t *Twenty) GetByte0() byte {
    return t[0]
}

So, it’s possible don’t to repeat the two methods GetByte0()?

To work the same way on different types, the types have to give up their individuality. Since Ten and Twenty share an underlying type there are two options:

package main

import "log"

func main() {
	log.SetFlags(log.Lshortfile)

	ten := &Ten{0: 10}
	twenty := &Twenty{0: 20}

	firstBytesSlice(ten[:], twenty[:])

	firstBytesInterface(ten, twenty)
}

type Ten [10]byte

func (t *Ten) GetByte0() byte {
	return t[0]
}

type Twenty [20]byte

func (t *Twenty) GetByte0() byte {
	return t[0]
}

func firstBytesSlice(slices ...[]byte) {
	for _, slice := range slices {
		log.Println(slice[0])
	}
}

func firstBytesInterface(firstBytes ...interface {
	GetByte0() byte
}) {
	for _, fb := range firstBytes {
		log.Println(fb.GetByte0())
	}
}

This outputs:

main.go:30: 10
main.go:30: 20
main.go:38: 10
main.go:38: 20

In Go, there is no inheritance, hence there is no notion of “base types”. I guess you mean that each of your structs has a different struct embedded, unlinke the exaple at Stackoverflow where both structs embed the same struct.

This is not a problem, though. Just create a struct that implements the common function and embed that struct, too. You will not get into the perils of multiple inheritance because, as mentioned, there is no inheritance in Go.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.