Go言語でポリモーフィズムを実装する方法

Go言語では、多態はインタフェースと型アサーションによって実現できます。

  1. インターフェースを用いて多態を実現する:

複数のメソッドを含むインターフェイスを定義します。

type Animal interface {
    Sound() string
}

複数の構造体を定義して、インターフェイスのメソッドを実装する。

type Dog struct{}

func (d Dog) Sound() string {
    return "汪汪汪"
}

type Cat struct{}

func (c Cat) Sound() string {
    return "喵喵喵"
}

ポリモーフィズムを使う:

func main() {
    animals := []Animal{Dog{}, Cat{}}

    for _, animal := range animals {
        fmt.Println(animal.Sound())
    }
}
  1. 多態を実現する型アサーションの使用:

任意の型を表す空インターフェースと呼ばれるinterface{}インターフェースを定義する

type Animal interface {
    Sound() string
}

複数構造体を定義し、インターフェイスのメソッドを実装します。

type Dog struct{}

func (d Dog) Sound() string {
    return "汪汪汪"
}

type Cat struct{}

func (c Cat) Sound() string {
    return "喵喵喵"
}

多態性を活用する

func main() {
    animals := []interface{}{Dog{}, Cat{}}

    for _, animal := range animals {
        if a, ok := animal.(Animal); ok {
            fmt.Println(a.Sound())
        }
    }
}

多態化を実装するには、上述2つの方法が利用可能ですが、実際の要求とコード設計によって、具体的な方法を選択する必要があります。

bannerAds