構造体とインターフェース
Go Struct Embedding and Composition
Go has no inheritance. Reuse fields and methods by embedding one struct in another.
学べること
- Embedding a struct
- Promoted fields and methods
- Composition
type Dog struct
DogAnimalName, Describe()Breed
Build types from smaller types
Go has no inheritance. Instead, a struct can embed another struct, and the fields and methods of the embedded type become available on the outer one. This is called composition.
Dog embeds Animal, so dog.Name and dog.Describe() work as if they were declared on Dog. The embedded value can still be reached by its type name, as in dog.Animal.Name. Service gets a Log method by embedding Logger.
重要なポイント
- Dog embeds Animal and gets Name and Describe.
- The embedded value is still reachable:
dog.Animal. - Embedding is composition, not inheritance.
実行できる Go のサンプル
Go
main.go
package main
import "fmt"
type Animal struct {
Name string
}
func (a Animal) Describe() string {
return a.Name + " is an animal"
}
type Dog struct {
Animal // embedded: Dog gets Name and Describe
Breed string
}
func (d Dog) Speak() string {
return d.Name + " says woof"
}
type Logger struct{ Prefix string }
func (l Logger) Log(message string) { fmt.Println(l.Prefix + message) }
type Service struct {
Logger
Name string
}
func main() {
dog := Dog{Animal: Animal{Name: "Rex"}, Breed: "Collie"}
fmt.Println(dog.Describe())
fmt.Println(dog.Speak())
fmt.Println(dog.Animal.Name, dog.Breed)
service := Service{Logger: Logger{Prefix: "[api] "}, Name: "users"}
service.Log("started " + service.Name)
}
Rex is an animal
Rex says woof
Rex Collie
[api] started users練習
サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。
このレッスンを終えましたか?
学習済みにすると進み具合を記録できます。
進み具合はこのブラウザーに保存されています ログインすると、どのデバイスでも引き継げます。
チャレンジで練習する
このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。
- 価格デコレーター 割引、税、送料、クーポンのデコレーターを順に適用して、基準価格を包む。 簡単
- コンポジットでフォルダーサイズ フォルダがファイルや他のフォルダを含む木構造で、すべてのフォルダの合計サイズを計算します。 中級