Go

Struct Embedding (Composition over Inheritance)

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Go has no inheritance. Embed a type to "promote" its fields and methods as if they were on the outer type. Same effect as inheritance for most purposes, but explicit.
Go
Raw
package main

import "fmt"

type Logger struct {
    prefix string
}

func (l *Logger) Log(msg string) {
    fmt.Printf("[%s] %s\n", l.prefix, msg)
}

type Server struct {
    *Logger                       // embedded — promotes Log() onto Server
    addr string
}

func (s *Server) Start() {
    s.Log("starting on " + s.addr)              // calls embedded Logger.Log
}

func main() {
    srv := &Server{
        Logger: &Logger{prefix: "SRV"},
        addr:   ":8080",
    }
    srv.Start()           // [SRV] starting on :8080
    srv.Log("manual")     // [SRV] manual
    // Access the embedded field directly if needed:
    fmt.Println(srv.Logger.prefix)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.