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:
| Parameter | Type | Description |
|---|---|---|
| Implicit Implementation | Design | Any type with matching method signatures satisfies interface automatically. |
Ready-to-Run Code Example
Executable in CompilraRun 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 pointerRelated Go Tutorials & Compiler
Go Methods and Receiver Functions: OOP Without Classes
Implement OOP methods in Go using value and pointer receivers on structs.
Go Multiple Return Values and Error Handling Signatures
Master Go signature multiple return values, named returns, and the idiomatic (result, error) convention without exceptions.
Go Error Handling: if err != nil, fmt.Errorf, and errors.Is
Master idiomatic Go error handling with explicit error checking and error wrapping (%w).
Go Online Compiler
Open in Compilra IDE
Run and test Go on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.