Kodewick
Comece a aprender →
Interfaces13 / 24

Interfaces em Go

Aula 13 de 24 · Parte 3 · Tipos · cerca de 15 minutos

Uma interface lista um conjunto de métodos, e qualquer tipo que tenha esses métodos a implementa automaticamente, sem nenhum «implements»; as mais comuns são fmt.Stringer e error.

Retângulos e círculos têm área, mas ela se calcula de jeitos diferentes. Uma interface descreve o que um valor sabe fazer: é um conjunto de métodos. Aqui, Shape pede um método, Area() float64, e describe aceita qualquer valor que o tenha:

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("Área: %.2f\n", s.Area())30}31 32func main() {33	describe(Rect{Width: 3, Height: 4})34	describe(Circle{Radius: 1})35}
Saída
Área: 12.00
Área: 3.14

Para describe, tanto faz se recebeu um retângulo ou um círculo; ela nem sabe. Só chama Area.

«interface»Shape
  • Area() float64
structRect
  • Width, Height
  • +Area()
structCircle
  • Radius
  • +Area()
Rect e Circle têm Area(), então os dois implementam Shape; describe só quer saber de Shape
Escolha uma

Que valores describe(s Shape) aceita?

Sem implements

Rect e Circle nunca dizem «eu sou um Shape». Em Go, um tipo que tem todos os métodos que uma interface pede implementa essa interface automaticamente; não existe a palavra-chave implements.

Uma variável de tipo interface pode guardar qualquer valor que a implemente, e o que ela guarda pode mudar:

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}
Saída
10
12.57
main.Circle

%T mostra o tipo do que s guarda naquele momento: main.Circle (o Circle do pacote main).

Adivinhe a saídaErrar não tem problema

O que este programa mostra?

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}

Formas diferentes num mesmo slice

Um []Shape pode guardar retângulos e círculos lado a lado. Um único laço soma as áreas:

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("Área total: %.2f\n", total)39}
Saída
Área total: 16.14

Se mais tarde você adicionar outro tipo de forma (um triângulo), desde que ele tenha Area, este laço não muda nada.

Escolha uma

Mais tarde você cria um Triangle. O que muda no laço que soma as áreas?

Exercício 1

O quadrado também é uma forma

Este programa não compila: Square ainda não é um Shape. Dê a Square um método Area (lado vezes lado) para que o programa mostre a área de cada forma.

Deveria mostrar
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}
Saída
Aperte Executar ou Ctrl+Enter

Um método que falta

Um tipo que não tem um método pedido pela interface não pode ser usado como essa interface. O compilador diz qual método está faltando:

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}
Saída
# 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 não tem método Area. Adicione func (t Triangle) Area() float64 e o programa compila.

Mais um caso: quando um método tem receptor ponteiro, só o ponteiro *Counter tem esse método, não o próprio Counter:

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}
Saída
# 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: o que entra na interface tem que ser &c. Chamar c.Inc() direto não dá problema, porque o Go pega o endereço da variável para você (aula 12); colocar c numa interface não faz isso, então você mesmo escreve &c. Faz sentido: se entrasse uma cópia de c, Inc mudaria a cópia.

colocar cvar i Incrementer = cerro de compilaçãoCounter não tem Inc
colocar &cvar i Incrementer = &cfunciona*Counter tem Inc
Inc tem receptor *Counter: o que vai na interface é &c
Adivinhe a saídaErrar não tem problema

O que isto mostra?

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

Por que o método String da aula 12 funcionava? O pacote fmt tem uma interface:

type Stringer interface { String() string }

Quando fmt.Println recebe um valor, primeiro confere se ele implementa fmt.Stringer; se implementar, chama String. Suas próprias funções também podem aceitar um fmt.Stringer:

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 anos)", e.Name, e.Age)12}13 14func introduce(s fmt.Stringer) {15	fmt.Println("Esta é " + s.String())16}17 18func main() {19	e := Employee{Name: "Maya", Age: 28}20	fmt.Println(e)21	introduce(e)22}
Saída
Maya (28 anos)
Esta é Maya (28 anos)
«interface»Stringer
  • String() string
structEmployee
  • Name
  • Age
  • +String()
Employee tem String() string, então implementa fmt.Stringer, e o fmt.Println chama esse método
Adivinhe a saídaErrar não tem problema

O que este programa mostra?

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}

A interface vazia: any

Uma interface que não pede nenhum método é interface{}, e o Go dá a ela um nome curto, any. Todos os tipos a implementam, então uma variável do tipo any pode guardar qualquer coisa:

prog.go
1package main2 3import "fmt"4 5func main() {6	var v any7	v = 428	fmt.Printf("%v %T\n", v, v)9	v = "olá"10	fmt.Printf("%v %T\n", v, v)11	things := []any{3, "caneta", 4.5, true}12	fmt.Println(things)13}
Saída
42 int
olá string
[3 caneta 4.5 true]

Os parâmetros de fmt.Println são any, e é por isso que ele mostra qualquer coisa. Mas, depois que um valor está dentro de um any, o Go só sabe que «é um valor», então você não pode somar nada a ele direto: primeiro precisa tirar o valor de lá.

Adivinhe a saídaErrar não tem problema

O que este programa mostra?

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}

Asserções de tipo

v.(int) é uma asserção de tipo (em inglês, *type assertion*): diz «v guarda um int» e tira o valor. Adicione um ok para perguntar antes:

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}
Saída
43
false true

v não guarda uma string, então ok é false e s é o valor zero "" (s == "" é true). Sem ok, se você errar, o programa entra em pânico:

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

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

O que aconteceu: The type assertion failed: the interface holds a different type.

interface conversion: interface {} is string, not int: v guarda uma string, não um int. (interface {} é any.) Quando não tiver certeza do que tem dentro, use a forma com ok.

CompleteToque numa para preencher um espaço; toque no espaço para tirar

Escolha um tipo para a lacuna, para o programa mostrar go true.

1package main2 3import "fmt"4 5func main() {6	var v any = "go"7	s, ok := v.()8	fmt.Println(s, ok)9}
Exercício 2

Some só os int

Termine sumInts: some os int de values, conte quantos não são int e devolva as duas coisas. Use uma asserção de tipo com ok. O programa testa dois grupos de valores.

Deveria mostrar
Soma dos int: 20 Outros: 3
Soma dos int: 10 Outros: 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, "caneta", 4.5, 7, true, 10})13	fmt.Println("Soma dos int:", sum, "Outros:", others)14	sum, others = sumInts([]any{"leite", 5, 5, 2.5})15	fmt.Println("Soma dos int:", sum, "Outros:", others)16}
Saída
Aperte Executar ou Ctrl+Enter

Type switch

Para tratar cada tipo de um jeito, use um type switch. Com switch x := v.(type), dentro de cada case a variável x tem o tipo daquele caso:

prog.go
1package main2 3import "fmt"4 5func describe(v any) string {6	switch x := v.(type) {7	case int:8		return fmt.Sprintf("um int; mais um dá %d", x+1)9	case string:10		return fmt.Sprintf("uma string de %d bytes", len(x))11	case bool:12		return "um valor verdadeiro/falso"13	default:14		return fmt.Sprintf("outro tipo: %T", x)15	}16}17 18func main() {19	for _, v := range []any{7, "go", true, 2.5} {20		fmt.Println(describe(v))21	}22}
Saída
um int; mais um dá 8
uma string de 2 bytes
um valor verdadeiro/falso
outro tipo: float64
Adivinhe a saídaErrar não tem problema

O que este programa mostra?

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}
Exercício 3

Que tipo tem dentro?

Termine kind: devolva número se v guardar um int, texto se guardar uma string e outro para qualquer outra coisa.

Deveria mostrar
número
texto
outro
número
exercise3.go
1package main2 3import "fmt"4 5func kind(v any) string {6	return "outro"7}8 9func main() {10	for _, v := range []any{10, "maçã", 3.5, -2} {11		fmt.Println(kind(v))12	}13}
Saída
Aperte Executar ou Ctrl+Enter

O que você aprendeu

  • Uma interface é um conjunto de métodos: type Shape interface { Area() float64 }.
  • Um tipo com todos esses métodos implementa a interface automaticamente, sem implements; um []Shape pode guardar tipos diferentes.
  • Um método faltando é um erro de compilação, does not implement … (missing method …); com métodos de receptor ponteiro, coloque &c.
  • fmt.Println usa a interface fmt.Stringer: se existir um String() string, ele chama.
  • any guarda qualquer coisa; v.(int) tira o valor e entra em pânico se você errar, enquanto n, ok := v.(int) não.
  • switch x := v.(type) trata cada tipo no seu próprio caso.
Terminou a aula 13?Aula 13 de 24 · o progresso fica neste navegador
A seguir · aula 14 · 15 minErrosTrate erros do jeito Go: resultados (valor, erro), if err != nil, errors.New, fmt.Errorf e %w, errors.Is e errors.As, e seus próprios tipos de erro.Próxima aula →
O botão marca esta aula como feita e abre a próxima.