Go:Go Interfaces and Struct Embedding (Composition Over Inheritance)
Go•Interfaces

Go Interfaces and Struct Embedding (Composition Over Inheritance)

In Go, interfaces are implemented implicitly without any implements keyword. Composition replaces classical inheritance.

Syntax

type Reader interface { Read(p []byte) (n int, err error) }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
Implicit ImplementationDesignAny type with matching method signatures satisfies interface automatically.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Go locally:

package main

import "fmt"

// Interface contract
type HealthChecker interface {
    CheckHealth() string
}

type DatabaseService struct {
    Name        string
    Connections int
}

// Implicit implementation of HealthChecker
func (db DatabaseService) CheckHealth() string {
    return fmt.Sprintf("%s: OK (%d active connections)", db.Name, db.Connections)
}

func runDiagnostic(h HealthChecker) {
    fmt.Println("[DIAGNOSTIC]", h.CheckHealth())
}

func main() {
    pg := DatabaseService{Name: "Postgres-Primary", Connections: 28}
    runDiagnostic(pg)
}
Expected Output:
[DIAGNOSTIC] Postgres-Primary: OK (Connections: 28)

How It Works: Step-by-Step

  • Lines 6-8: Defines HealthChecker interface.
  • Lines 16-18: DatabaseService implements CheckHealth() matching the interface signature.
  • Line 25: Passes DatabaseService directly to function accepting HealthChecker.

Key Concepts

  • No implements keyword is required; Go checks interfaces at compile time.
  • Small, single-method interfaces (Reader, Writer) are idiomatic in Go.
  • Empty interface any (or interface{}) accepts values of any type.

Common Mistake: Implementing interface with pointer receiver and passing value type

If a method has pointer receiver (db *DB), a plain value DB does not implement the interface.

❌ Incorrect
func (db *DB) CheckHealth() string; var h HealthChecker = DB{} // Compile Error!
✅ Correct
var h HealthChecker = &DB{} // Pass pointer

Related Go Tutorials & Compiler

Run and test Go on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Go Online Compiler