LoginSignup
7
7

More than 5 years have passed since last update.

[Go言語] 埋め込んだときに、メソッド名が被っててインタフェースを実装できない場合はどうするのか?

Posted at

明示的に判別ないとインタフェースの型として振る舞えない

以下のように、同じNameというメソッドを持つ構造体を埋め込むと、NamedというNameを持つインタフェースを実装できない。
なぜならば、HogeNameを呼べばいいのか、PiyoNameを呼べばいいのか分からない。
もちろん、Foo型として振る舞っているときは明示的に埋め込んでいる型を指定すれば、呼び出せる。

package main

import "fmt"

type Named interface {
    Name() string
}

type Hoge struct {
}

func (_ *Hoge) Name() string {
    return "Hoge"
}

func (_ *Hoge) HogeMethod() {
    fmt.Println("Hoge Method!")
}

type Piyo struct {
}

func (_ *Piyo) Name() string {
    return "Piyo"
}

func (_ *Piyo) PiyoMethod() {
    fmt.Println("Piyo Method!")
}

type Foo struct {
    *Hoge
    *Piyo
}

func hello(named Named) {
    fmt.Println("Hello", named.Name())
}

func main() {
    hoge := &Hoge{}
    piyo := &Piyo{}
    foo := &Foo{hoge, piyo}

    fmt.Println(foo.Hoge.Name())
    fmt.Println(foo.Piyo.Name())

    foo.HogeMethod()
    foo.PiyoMethod()

    hello(foo)
}

明示的に定義する

どっちか分からないならFooのメソッドとして、明示定義してやればいい。

func (f *Foo) Name() string {
    return f.Piyo.Name()
}
7
7
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
7
7