Kodewick
Jetzt lernen →
Interfaces13 / 24

Interfaces in Go

Lektion 13 von 24 · Teil 3 · Typen · etwa 15 Minuten

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:

prog.go
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}
Ausgabe
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.

«interface»Shape
  • Area() float64
structRect
  • Width, Height
  • +Area()
structCircle
  • Radius
  • +Area()
Rect und Circle haben beide Area(), also implementieren beide Shape; describe kennt nur Shape
Eine wählen

Welche Werte nimmt describe(s Shape) an?

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:

prog.go
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}
Ausgabe
10
12.57
main.Circle

%T zeigt den Typ dessen, was s gerade enthält: main.Circle (das Circle im Paket main).

Ausgabe ratenFalsch raten ist okay

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}

Verschiedene Formen in einem Slice

Ein []Shape kann Rechtecke und Kreise nebeneinander enthalten. Eine einzige Schleife zählt ihre Flächen zusammen:

prog.go
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}
Ausgabe
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.

Eine wählen

Später kommt ein Triangle dazu. Was musst du an der Schleife ändern, die die Flächen addiert?

Übung 1

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.

Es soll ausgeben
6
9
25
exercise1.go
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}
Ausgabe
Drück auf Ausführen oder Strg+Enter

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:

prog.go
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}
Ausgabe
# 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:

prog.go
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}
Ausgabe
# 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.

c reinvar i Incrementer = cCompilerfehlerCounter hat kein Inc
&c reinvar i Incrementer = &cklappt*Counter hat Inc
Inc hat einen *Counter-Empfänger: Ins Interface gehört &c
Ausgabe ratenFalsch raten ist okay

Was 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}

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:

prog.go
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}
Ausgabe
Maya (28 Jahre)
Das ist Maya (28 Jahre)
«interface»Stringer
  • String() string
structEmployee
  • Name
  • Age
  • +String()
Employee hat String() string, implementiert also fmt.Stringer, und fmt.Println ruft es auf
Ausgabe ratenFalsch raten ist okay

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}

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:

prog.go
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}
Ausgabe
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.

Ausgabe ratenFalsch raten ist okay

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}

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:

prog.go
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}
Ausgabe
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:

prog.go
1package main2 3import "fmt"4 5func main() {6	var v any = "42"7	n := v.(int)8	fmt.Println(n)9}
Ausgabe
panic: interface conversion: interface {} is string, not int

goroutine 1 [running]:
main.main(...)
	/tmp/sandbox/prog.go:7 +0x1d
exit status 2

Was 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.

Lücke füllenTippe ein Wort für eine Lücke; tippe die Lücke, um es zurückzunehmen

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}
Übung 2

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.

Es soll ausgeben
Summe der ints: 20 Andere: 3
Summe der ints: 10 Andere: 2
exercise2.go
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}
Ausgabe
Drück auf Ausführen oder Strg+Enter

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:

prog.go
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}
Ausgabe
ein int, plus eins ist 8
ein String mit 2 Bytes
ein Wahrheitswert
ein anderer Typ: float64
Ausgabe ratenFalsch raten ist okay

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}
Übung 3

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.

Es soll ausgeben
Zahl
Text
anderes
Zahl
exercise3.go
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}
Ausgabe
Drück auf Ausführen oder Strg+Enter

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 []Shape kann verschiedene Typen enthalten.
  • Eine fehlende Methode ist ein Kompilierfehler, does not implement … (missing method …); bei Methoden mit Zeiger-Receiver steckst du &c hinein.
  • fmt.Println benutzt das Interface fmt.Stringer: Gibt es ein String() string, ruft es das auf.
  • any enthä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.
Lektion 13 geschafft?Lektion 13 von 24 · der Fortschritt bleibt in diesem Browser
Als Nächstes · Lektion 14 · 15 Min.FehlerBehandle Fehler auf die Go-Art: Ergebnisse (Wert, error), if err != nil, errors.New, fmt.Errorf und %w, errors.Is und errors.As, eigene Fehlertypen.Nächste Lektion →
Der Button markiert diese Lektion als erledigt und öffnet die nächste.