Golangでメソッドのオーバーライドをする方法




structのメソッドを別のstructで使い回す

Golangにはクラスはありませんがstructを使って似た機能を定義することができます。

このstructを別のstructに埋め込むことで別のstructからも同じメソッドを使用することができます。

type Parent struct {
	name string
}

func (p *Parent) printName() {
	log.Println(p.name)
}

type Child struct {
	Parent
}

func main() {
	p := &Parent{
		name: "parent"
	}
	c := &Child{ *p }
	c.printName() // "Parent"
}

Parent structを使ってChild structを生成します。

生成したChildからParentのprintNameメソッドを呼び出すことができます。

structのメソッドをオーバーライドする

埋め込んだstructのメソッドをそのまま使うこともできるし、同名のメソッドを定義することでオーバーライドすることができます。

クラスではないですが、Golangでも同様の使い方ができるのでぜひ試してみてください。

type Parent struct {
	name string
}

func (p *Parent) printName() {
	log.Println(p.name)
}

type Child struct {
	Parent
}

func (p *Child) printName() {
	log.Println("Child")
}

func main() {
	p := &Parent{
		name: "parent"
	}
	c := &Child{ *p }
	c.printName() // "Child"
}

 

The following two tabs change content below.

髙妻智一

2013年CyberAgent新卒入社 スマホゲームを作る子会社に所属し、サーバーサイドのエンジニアを担当。2年目の終わりから新規子会社の立ち上げに参加し、サーバーサイドのエンジニアリーダーとしてサービースのリリースから運用までを担当。 2018年仮想通貨のスマホウォレットを提供するGinco Incにブロックチェーンエンジニアとして入社。






よく読まれている関連記事はこちら




コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です