How can two different types implement the same method in golang using interfaces?

No you can’t, but you could create a base type and then embed it into your 2 struct, therefore only needing an implementation for the base type:

type WithString struct {
    str string
}

type First struct {
    WithString
}

type Second struct {
    WithString
}

type A interface {
    PrintStr() //print First.str or Second.str
}

func (w WithString) PrintStr() {
    fmt.Print(w.str)
}

Usage:

a := First{
    WithString: WithString{
        str: "foo",
    },
}

Complete Example on Playground

Embed documentation

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)