IntermediateLesson 8 of 15
Interfaces – Go
Implicit contracts, type assertions and the empty interface type.
An interface describes methods. A type implements it automatically as soon as it has all the methods – without implements. This decouples your code: functions accept interfaces and work with any matching type.
package main
import (
"fmt"
"math"
)
type Form interface {
Flaeche() float64
Umfang() float64
}
type Rechteck struct{ B, H float64 }
type Kreis struct{ R float64 }
func (r Rechteck) Flaeche() float64 { return r.B * r.H }
func (r Rechteck) Umfang() float64 { return 2 * (r.B + r.H) }
func (k Kreis) Flaeche() float64 { return math.Pi * k.R * k.R }
func (k Kreis) Umfang() float64 { return 2 * math.Pi * k.R }
func main() {
formen := []Form{Rechteck{3, 4}, Kreis{1}}
for _, f := range formen {
fmt.Printf("%T %.2f\n", f, f.Flaeche())
}
// main.Rechteck 12.00
// main.Kreis 3.14
}The standard library thrives on small interfaces: io.Reader (one method Read), io.Writer, fmt.Stringer, error. The empty type any (an alias for interface{}) accepts any value. You get the concrete type back with a type assertion or type switch.
package main
import "fmt"
func beschreibe(v any) string {
switch x := v.(type) {
case nil:
return "nil"
case int:
return fmt.Sprintf("int %d", x)
case string:
return "string " + x
case fmt.Stringer:
return "Stringer " + x.String()
default:
return fmt.Sprintf("unknown %T", x)
}
}
func main() {
fmt.Println(beschreibe(42)) // int 42
fmt.Println(beschreibe("Go")) // string Go
fmt.Println(beschreibe(3.5)) // unbekannt float64
var v any = "text"
if s, ok := v.(string); ok {
fmt.Println("String with length", len(s)) // String with length 4
}
}TipRule of thumb: "Accept interfaces, return structs" – parameters as interfaces, return values as concrete types. Define interfaces where they are used, and keep them small.
WarningThe nil trap: an interface value is only
nil if type and value are nil. If you return a *MeinFehler with value nil as an error, then err != nil is true! In such cases, explicitly return nil.