Sobes.tech
Middle

Which mechanism exists in Go — inheritance or composition?

sobes.tech AI

Answer from AI

Go lacks classical inheritance like in object-oriented languages such as Java or C++. Instead, Go uses composition and interfaces for code reuse and polymorphism.

Composition in Go is achieved by embedding one type into another as an unnamed field (embedding). This allows the new type to automatically have the methods of the embedded type, which is similar to inheritance but more flexible and explicit.

Example of composition:

 type Logger struct {
     prefix string
 }

 func (l Logger) Log(message string) {
     fmt.Println(l.prefix, message)
 }

// Embedding Logger into App

type App struct {
     Logger
     name string
 }

func main() {
     app := App{
         Logger: Logger{prefix: "[App]"},
         name:   "MyApp",
     }
     app.Log("started") // calling Logger method via composition
}

Thus, composition is the main mechanism for code reuse and extending functionality in Go.

Which mechanism exists in Go — inheritance or… - sobes.tech