Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Composition over Inheritance | Methods, Interfaces, and Composition
Advanced Go

bookComposition over Inheritance

Свайпніть щоб показати меню

Composition Over Inheritance

Go uses composition rather than classical inheritance to share functionality between types. Instead of creating hierarchies with parent and child classes, you embed one struct inside another. This is called struct embedding.

With struct embedding, you place one struct as a field in another struct—without a field name. The outer struct automatically gains access to the methods of the embedded struct, as if they were its own. This provides code reuse, but avoids the tight coupling and complexity of inheritance chains found in other languages.

This approach promotes flexible design. You can mix and match behaviors by embedding different structs, creating types with only the features you need. There is no "is-a" relationship—composition models "has-a" or "can-do" relationships, making your codebase easier to maintain and extend.

main.go

main.go

copy
1234567891011121314151617181920212223
package main import ( "fmt" ) // Logger provides logging functionality. type Logger struct{} func (l Logger) Log(message string) { fmt.Println("LOG:", message) } // User embeds Logger to gain logging ability without inheritance. type User struct { Name string Logger // Embedded struct } func main() { user := User{Name: "Alice"} user.Log("User created: " + user.Name) }
question mark

Which statement best describes the benefit of struct embedding in Go compared to traditional inheritance?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 2

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 1. Розділ 2
some-alt