LoginSignup
1
0

More than 5 years have passed since last update.

Go言語での継承についての色々

Last updated at Posted at 2019-02-23

説明

と言っても、既知のものを組合わせただけで真新しいものは何もない。

よくあるパターンとして、interfaceを定義して、それの実装structを用意する。

type Hoge interface {
  Func1()
  Func2()
}

type hoge struct {
}

func (h hoge) Func1(){}
func (h hoge) Func2(){}

こんな感じ。

で、実装structが一つの場合は良いけど、複数ある場合に同じような処理をその複数で実装するとD.R.Yに反するので、どうにかしたいと思うこともあるはず。

そんな時に使えるのが、temporarystructを作ると良い。

type _hoge struct {
}

func (h _hoge) Func1(){ ... }
func (h _hoge) Func2(){ ... }

type hoge1 struct {
  _hoge
}

type hoge2 struct {
  _hoge
}

とやると、

h1 := &hoge1{}
h2 := &hoge1{}
h1.Func1()
h2.Func1()

というのができる。

もちろんフィールドも使うことができる。

type Hoge interface {
  Func1()
  Func2()
}

type hoge struct {
  f1 int
  f2 string
}

func (h hoge) Func1() int {
  return h.f1
}
func (h hoge) Func2() string {
  return h.f2
}

type hoge1 struct {
  _hoge
}

となった時に、

h1 := &hoge1{}
h1.f1 = 5
h1.f2 = "test"

v1 := h1.Func1()
> 5
v2 := h2.Func1()
> test

となる。

ただこのままだと、

h1 := &hoge1{
  f1: 5,
  f2: "test",
}

とはできない。
なぜなら、hogef1f2が定義されていないから。

とは言えども、定義したらしたらで別問題が発生。

type hoge1 struct {
  _hoge
  f1 int
  f2 string
}

としたら、

h1 := &hoge1{
  f1: 5,
  f2: "test",
}

としたらエラーにはならないけど、

v1 := h1.Func1()
> 0
v2 := h2.Func1()
> 

となる。
それは、フィールドを定義しているところが違うから。
もし定義前と同じようにしたければ、

func (h hoge) Func1() int {
  return h._hoge.f1
}
func (h hoge) Func2() string {
  return h._hoge.f2
}

としたら良い。

あとは、今までの流れを組合わせたら問題は解決できるはず。

お願い

訂正、補足などありましたら、適宜コメントお願いします。

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