LoginSignup
1
0

More than 1 year has passed since last update.

Go言語オーバーライド例

Last updated at Posted at 2023-01-18

やりたいこと
親structを取り込み子struct側のメソッドでオーバーライドさせます。

親のみ

// maing.go
package main

import (
	"fmt"
)

type Parent struct {
	NameParent string
}

func main() {
	c := Parent{"親"}
	c.Method()
}

func (p *Parent) Method() {
	fmt.Println(p.NameParent)
}

結果

親を取り込みオーバーライド
Parentをembeddedフィールドとして取り込み、Methodレシーバで値を操作する。

// main.go
package main

import (
	"fmt"
)

type Parent struct {
	NameParent string
}

type Child struct {
	Parent // embedded
	NameChild string
}

func main() {
	// 親の値を取得
	p := GetParent()
	// 親の値を子が取り込む
	c := Child{Parent: p, NameChild: "子"}
    // オーバライドのほうが呼ばれる
	c.Method()
}

func GetParent() Parent {
	p := Parent{"親"}
	return p
}

// 使われない
func (p *Parent) Method() {
	fmt.Println(p.NameParent)
}

// オーバーライド
func (c *Child) Method() {
	c.NameParent = "変更した親"
	c.NameChild = "変更した子"
	fmt.Println(c.Parent.NameParent + "の" + c.NameChild)
}

結果
変更した親の変更した子

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0