LoginSignup
11

More than 5 years have passed since last update.

埋め込みを他のパッケージから隠蔽する #golang

Posted at

以下の記事にも書いているが,構造体型へ別の型を匿名フィールドとして埋め込む場合,型がパッケージ外に公開してあると,パッケージ外からその匿名フィールドにアクセスできてしまう.

たとえば,以下のようにHoge型に*Fuga型を埋め込んだ場合,Fuga型はパッケージ外に公開されているため,埋め込んだFuga型の値にもアクセスできてしまう.

type Fuga struct {
}

type Hoge struct {
    *Fuga
}
// パッケージ外からもアクセスできる
hoge := &Hoge{&Fuga{}}
hoge.Fuga = nil

また,パッケージ外に公開されていない型を埋め込んだ場合は,パッケージ外からアクセスできない.

type fuga struct {
}

type Hoge struct {
    *fuga
}

func NewHoge() *Hoge {
    return &Hoge{&fuga{}}
}
// パッケージ外からはアクセスできない
hoge := pkg.NewHoge()
hoge.fuga = nil

そこで,公開されている型を埋め込みたい場合は,以下のようにtypeで新しく公開されない型を作ってやればよい.

type Fuga struct {
}

type fuga Fuga

type Hoge struct {
    *fuga
}

func NewHoge() *Hoge {
    return &Hoge{&fuga{}}
}

もちろん,埋め込む型が構造体型じゃなくても問題ない.

type stringer fmt.Stringer

type Hoge struct {
    stringer
}

func NewHoge(s fmt.Stringer) *Hoge {
    return &Hoge{stringer(s)}
}

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
11