LoginSignup
0
0

More than 3 years have passed since last update.

Go で同じフィールドを持つ構造体を interface で定義する

Last updated at Posted at 2020-09-04

Go の interface は、メソッドを定義することはできますが、フィールドを定義することはできません。
代わりに Getter(必要に応じて Setter)を定義して同じフィールドを持つことを保証することができます。

type Animal interface {
  GetName() string
}

type Dog struct {
  Name string
}

func (d *Dog) GetName() string {
  return d.Name
}

type Cat struct {
  Name string
}

func (c *Cat) GetName() string {
  return c.Name
}

func greet(animal Animal) {
  fmt.Printf("Hello, %s!\n", animal.GetName())
}

フィールドにアクセスする必要すらない場合は空のメソッドを定義します。

type Animal interface {
  animal()
}

type Dog struct {
  Name string
}

func (d *Dog) animal() {}

type Cat struct {
  Name string
}

func (c *Cat) animal() {}

func greet(animal Animal) {
  fmt.Printf("Hello, %T!\n", animal)
}

補足

フィールド Name が unexported(つまり name)ならば GetName ではなく Name のように命名するのが推奨されています。
Effective Go - The Go Programming Language

0
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
0
0