Interfaces in Go
Ein Interface listet eine Reihe von Methoden auf, und jeder Typ mit diesen Methoden implementiert es automatisch, ohne „implements“; häufige sind fmt.Stringer und error.
Rechtecke und Kreise haben beide eine Fläche, nur wird sie verschieden berechnet. Ein Interface beschreibt, was ein Wert kann: Es ist eine Menge von Methoden. Hier verlangt Shape eine Methode, Area() float64, und describe nimmt jeden Wert, der sie hat:
1package main2 3import (4 "fmt"5 "math"6)7 8type Shape interface {9 Area() float6410}11 12type Rect struct {13 Width, Height float6414}15 16func (r Rect) Area() float64 {17 return r.Width * r.Height18}19 20type Circle struct {21 Radius float6422}23 24func (c Circle) Area() float64 {25 return math.Pi * c.Radius * c.Radius26}27 28func describe(s Shape) {29 fmt.Printf("Fläche: %.2f\n", s.Area())30}31 32func main() {33 describe(Rect{Width: 3, Height: 4})34 describe(Circle{Radius: 1})35}
Fläche: 12.00 Fläche: 3.14
describe weiß nicht, ob es ein Rechteck oder einen Kreis bekommen hat, und es ist ihm auch egal. Es ruft einfach Area auf.
Area() float64
Width, Height
- +
Area()
Radius
- +
Area()
Welche Werte nimmt describe(s Shape) an?
describe ruft nur Area auf, verlangt also nur diese eine Methode. Ein Schlüsselwort implements gibt es in Go gar nicht.Kein implements nötig
Rect und Circle sagen nirgends „Ich bin ein Shape“. In Go implementiert ein Typ, der alle Methoden hat, die ein Interface verlangt, dieses Interface automatisch; ein Schlüsselwort implements gibt es nicht.
Eine Variable vom Typ eines Interface kann jeden Wert enthalten, der es implementiert, und was sie enthält, kann sich ändern:
1package main2 3import (4 "fmt"5 "math"6)7 8type Shape interface {9 Area() float6410}11 12type Rect struct {13 Width, Height float6414}15 16func (r Rect) Area() float64 {17 return r.Width * r.Height18}19 20type Circle struct {21 Radius float6422}23 24func (c Circle) Area() float64 {25 return math.Pi * c.Radius * c.Radius26}27 28func main() {29 var s Shape30 s = Rect{Width: 2, Height: 5}31 fmt.Println(s.Area())32 s = Circle{Radius: 2}33 fmt.Printf("%.2f\n", s.Area())34 fmt.Printf("%T\n", s)35}
10 12.57 main.Circle
%T zeigt den Typ dessen, was s gerade enthält: main.Circle (das Circle im Paket main).
Was gibt dieses Programm aus?
1package main2 3import (4 "fmt"5 "math"6)7 8type Shape interface {9 Area() float6410}11 12type Rect struct {13 Width, Height float6414}15 16func (r Rect) Area() float64 {17 return r.Width * r.Height18}19 20type Circle struct {21 Radius float6422}23 24func (c Circle) Area() float64 {25 return math.Pi * c.Radius * c.Radius26}27 28func main() {29 var s Shape = Circle{Radius: 1}30 s = Rect{Width: 2, Height: 5}31 fmt.Printf("%v %T\n", s.Area(), s)32}
Rect in s: Fläche 2 × 5 = 10. %T zeigt den Typ, den s gerade enthält, nicht Shape.Verschiedene Formen in einem Slice
Ein []Shape kann Rechtecke und Kreise nebeneinander enthalten. Eine einzige Schleife zählt ihre Flächen zusammen:
1package main2 3import (4 "fmt"5 "math"6)7 8type Shape interface {9 Area() float6410}11 12type Rect struct {13 Width, Height float6414}15 16func (r Rect) Area() float64 {17 return r.Width * r.Height18}19 20type Circle struct {21 Radius float6422}23 24func (c Circle) Area() float64 {25 return math.Pi * c.Radius * c.Radius26}27 28func main() {29 shapes := []Shape{30 Rect{Width: 3, Height: 4},31 Circle{Radius: 1},32 Rect{Width: 1, Height: 1},33 }34 total := 0.035 for _, s := range shapes {36 total += s.Area()37 }38 fmt.Printf("Gesamtfläche: %.2f\n", total)39}
Gesamtfläche: 16.14
Kommt später eine neue Art von Form dazu (ein Dreieck), ändert sich diese Schleife überhaupt nicht, solange die Form Area hat.
Später kommt ein Triangle dazu. Was musst du an der Schleife ändern, die die Flächen addiert?
s.Area() auf, egal welche Form in s steckt. Ein neuer Typ mit Area passt in ein []Shape, und die Schleife funktioniert weiter.Ein Quadrat wird auch eine Form
✓Dieses Programm kompiliert nicht: Square ist noch kein Shape. Gib Square eine Methode Area (Seite mal Seite), damit das Programm die Fläche jeder Form ausgibt.
6 9 25
1package main2 3import "fmt"4 5type Shape interface {6 Area() float647}8 9type Rect struct {10 Width, Height float6411}12 13func (r Rect) Area() float64 {14 return r.Width * r.Height15}16 17type Square struct {18 Side float6419}20 21func main() {22 shapes := []Shape{Rect{Width: 2, Height: 3}, Square{Side: 3}, Square{Side: 5}}23 for _, s := range shapes {24 fmt.Println(s.Area())25 }26}
Eine fehlende Methode
Ein Typ, dem eine Methode fehlt, die das Interface verlangt, kann nicht als dieses Interface benutzt werden. Der Compiler nennt die fehlende Methode:
1package main2 3import "fmt"4 5type Shape interface {6 Area() float647}8 9type Triangle struct {10 Base, Height float6411}12 13func main() {14 var s Shape = Triangle{Base: 3, Height: 4}15 fmt.Println(s.Area())16}
# command-line-arguments
./prog.go:14:16: cannot use Triangle{…} (value of struct type Triangle) as Shape value in variable declaration: Triangle does not implement Shape (missing method Area)Triangle does not implement Shape (missing method Area): Triangle hat keine Methode Area. Schreib func (t Triangle) Area() float64 dazu, dann kompiliert es.
Noch ein Fall: Hat eine Methode einen Zeiger-Receiver, dann hat nur der Zeiger *Counter diese Methode, nicht Counter selbst:
1package main2 3import "fmt"4 5type Counter struct {6 N int7}8 9func (c *Counter) Inc() {10 c.N++11}12 13type Incrementer interface {14 Inc()15}16 17func main() {18 var c Counter19 var i Incrementer = c20 i.Inc()21 fmt.Println(c.N)22}
# command-line-arguments
./prog.go:19:22: cannot use c (variable of struct type Counter) as Incrementer value in variable declaration: Counter does not implement Incrementer (method Inc has pointer receiver)method Inc has pointer receiver: Ins Interface muss &c. c.Inc() direkt aufzurufen geht, weil Go die Adresse der Variable für dich nimmt (Lektion 12); wenn du c in ein Interface steckst, passiert das nicht, also schreibst du &c selbst. Das ergibt Sinn: Käme eine Kopie von c hinein, würde Inc die Kopie ändern.
var i Incrementer = cCompilerfehlerCounter hat kein Incvar i Incrementer = &cklappt*Counter hat IncWas gibt das aus?
1package main2 3import "fmt"4 5type Counter struct {6 N int7}8 9func (c *Counter) Inc() {10 c.N++11}12 13type Incrementer interface {14 Inc()15}16 17func main() {18 var c Counter19 var i Incrementer = &c20 i.Inc()21 i.Inc()22 fmt.Println(c.N)23}
i enthält einen Zeiger auf c, also ändert i.Inc() das c. Es wird zweimal aufgerufen, also ist die Antwort 2.fmt.Stringer
Warum hat die Methode String aus Lektion 12 funktioniert? Das Paket fmt hat ein Interface:
type Stringer interface { String() string }
Bekommt fmt.Println einen Wert, prüft es zuerst, ob der Wert fmt.Stringer implementiert; wenn ja, ruft es String auf. Auch deine eigenen Funktionen können einen fmt.Stringer nehmen:
1package main2 3import "fmt"4 5type Employee struct {6 Name string7 Age int8}9 10func (e Employee) String() string {11 return fmt.Sprintf("%s (%d Jahre)", e.Name, e.Age)12}13 14func introduce(s fmt.Stringer) {15 fmt.Println("Das ist " + s.String())16}17 18func main() {19 e := Employee{Name: "Maya", Age: 28}20 fmt.Println(e)21 introduce(e)22}
Maya (28 Jahre) Das ist Maya (28 Jahre)
String() string
NameAge
- +
String()
Was gibt dieses Programm aus?
1package main2 3import "fmt"4 5type Point struct {6 X, Y int7}8 9func (p Point) String() string {10 return fmt.Sprintf("(%d, %d)", p.X, p.Y)11}12 13func main() {14 fmt.Println(Point{X: 3, Y: 4})15}
Point hat String() string, also ruft fmt.Println diese Methode auf und zeigt (3, 4). Ohne sie stünde da {3 4}.Das leere Interface: any
Ein Interface, das gar keine Methoden verlangt, ist interface{}, und Go gibt ihm einen kurzen Namen: any. Jeder Typ implementiert es, also kann eine Variable vom Typ any alles enthalten:
1package main2 3import "fmt"4 5func main() {6 var v any7 v = 428 fmt.Printf("%v %T\n", v, v)9 v = "hallo"10 fmt.Printf("%v %T\n", v, v)11 things := []any{3, "Stift", 4.5, true}12 fmt.Println(things)13}
42 int hallo string [3 Stift 4.5 true]
Die Parameter von fmt.Println sind any, deshalb kann es alles ausgeben. Aber steckt ein Wert erst einmal in einem any, weiß Go nur noch „es ist ein Wert“, also kannst du nicht direkt etwas dazuzählen: Zuerst musst du den Wert wieder herausholen.
Was gibt dieses Programm aus?
1package main2 3import "fmt"4 5func main() {6 things := []any{1, "a", true}7 fmt.Printf("%T %T %T\n", things[0], things[1], things[2])8}
%T zeigt den Typ des Werts im any: 1 ist ein int, "a" ein string, true ein bool.Typzusicherungen
v.(int) ist eine Typzusicherung (type assertion): Sie sagt „v enthält einen int“ und holt ihn heraus. Mit einem ok dazu fragst du vorher nach:
1package main2 3import "fmt"4 5func main() {6 var v any = 427 n := v.(int)8 fmt.Println(n + 1)9 s, ok := v.(string)10 fmt.Println(ok, s == "")11}
43 false true
v enthält keinen string, also ist ok gleich false und s der Nullwert "" (s == "" ist true). Ohne ok löst eine falsche Vermutung einen Panic aus:
1package main2 3import "fmt"4 5func main() {6 var v any = "42"7 n := v.(int)8 fmt.Println(n)9}
panic: interface conversion: interface {} is string, not int
goroutine 1 [running]:
main.main(...)
/tmp/sandbox/prog.go:7 +0x1d
exit status 2Was passiert ist: The type assertion failed: the interface holds a different type.
interface conversion: interface {} is string, not int: v enthält einen string, keinen int. (interface {} ist any.) Wenn du nicht sicher bist, was drinsteckt, nimm die Form mit ok.
Wähl einen Typ für die Lücke, damit das Programm go true ausgibt.
1package main2 3import "fmt"4 5func main() {6 var v any = "go"7 s, ok := v.()8 fmt.Println(s, ok)9}
v steckt ein string, die Typzusicherung v.(string) stimmt also: s ist "go", ok ist true. Mit int käme 0 false heraus.Nur die ints zusammenzählen
✓Mach sumInts fertig: Zähl die ints in values zusammen, zähl, wie viele keine ints sind, und gib beides zurück. Nimm eine Typzusicherung mit ok. Das Programm probiert zwei Sätze von Werten aus.
Summe der ints: 20 Andere: 3 Summe der ints: 10 Andere: 2
1package main2 3import "fmt"4 5func sumInts(values []any) (int, int) {6 sum := 07 others := 08 return sum, others9}10 11func main() {12 sum, others := sumInts([]any{3, "Stift", 4.5, 7, true, 10})13 fmt.Println("Summe der ints:", sum, "Andere:", others)14 sum, others = sumInts([]any{"Milch", 5, 5, 2.5})15 fmt.Println("Summe der ints:", sum, "Andere:", others)16}
Typ-Switches
Um jeden Typ anders zu behandeln, nimm einen Typ-Switch. Mit switch x := v.(type) hat die Variable x in jedem case den Typ dieses Falls:
1package main2 3import "fmt"4 5func describe(v any) string {6 switch x := v.(type) {7 case int:8 return fmt.Sprintf("ein int, plus eins ist %d", x+1)9 case string:10 return fmt.Sprintf("ein String mit %d Bytes", len(x))11 case bool:12 return "ein Wahrheitswert"13 default:14 return fmt.Sprintf("ein anderer Typ: %T", x)15 }16}17 18func main() {19 for _, v := range []any{7, "go", true, 2.5} {20 fmt.Println(describe(v))21 }22}
ein int, plus eins ist 8 ein String mit 2 Bytes ein Wahrheitswert ein anderer Typ: float64
Was gibt dieses Programm aus?
1package main2 3import "fmt"4 5func size(v any) int {6 switch x := v.(type) {7 case int:8 return x9 case string:10 return len(x)11 default:12 return -113 }14}15 16func main() {17 fmt.Println(size(7), size("hello"), size(2.5))18}
7 ist ein int und kommt unverändert zurück; "hello" ist ein string, also kommt seine Länge 5; 2.5 ist ein float64, landet bei default und ergibt -1.Welcher Typ steckt drin?
✓Mach kind fertig: Gib Zahl zurück, wenn v einen int enthält, Text, wenn es einen string enthält, und anderes für alles andere.
Zahl Text anderes Zahl
1package main2 3import "fmt"4 5func kind(v any) string {6 return "anderes"7}8 9func main() {10 for _, v := range []any{10, "Apfel", 3.5, -2} {11 fmt.Println(kind(v))12 }13}
Das hast du gelernt
- Ein Interface ist eine Menge von Methoden:
type Shape interface { Area() float64 }. - Ein Typ mit allen Methoden implementiert das Interface automatisch, ohne
implements; ein[]Shapekann verschiedene Typen enthalten. - Eine fehlende Methode ist ein Kompilierfehler,
does not implement … (missing method …); bei Methoden mit Zeiger-Receiver steckst du&chinein. fmt.Printlnbenutzt das Interfacefmt.Stringer: Gibt es einString() string, ruft es das auf.anyenthält alles;v.(int)holt den Wert heraus und löst bei einer falschen Vermutung einen Panic aus,n, ok := v.(int)dagegen nicht.switch x := v.(type)behandelt jeden Typ in einem eigenen Fall.