Interfaces em Go
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:
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}
Á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.
Area() float64
Width, Height
- +
Area()
Radius
- +
Area()
Que valores describe(s Shape) aceita?
describe só chama Area, então a única exigência é ter esse método. Em Go nem existe a palavra implements.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:
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 mostra o tipo do que s guarda naquele momento: main.Circle (o Circle do pacote main).
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}
s é um Rect: a área é 2 × 5 = 10. %T mostra o tipo que s guarda agora, não Shape.Formas diferentes num mesmo slice
Um []Shape pode guardar retângulos e círculos lado a lado. Um único laço soma as áreas:
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}
Á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.
Mais tarde você cria um Triangle. O que muda no laço que soma as áreas?
s.Area() e não liga para qual forma está em s. Um tipo novo com Area cabe num []Shape, e o laço continua funcionando.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.
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}
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:
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 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:
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: 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.
var i Incrementer = cerro de compilaçãoCounter não tem Incvar i Incrementer = &cfunciona*Counter tem IncO 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}
i guarda um ponteiro para c, então i.Inc() muda c. Ele é chamado duas vezes, então a resposta é 2.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:
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}
Maya (28 anos) Esta é Maya (28 anos)
String() string
NameAge
- +
String()
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}
Point tem String() string, então o fmt.Println chama esse método e mostra (3, 4). Sem ele, você veria {3 4}.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:
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}
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á.
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}
%T mostra o tipo do valor que está dentro do any: 1 é int, "a" é string e true é bool.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:
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 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:
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 2O 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.
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}
v guarda uma string, então a asserção v.(string) acerta: s é "go" e ok é true. Com int sairia 0 false.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.
Soma dos int: 20 Outros: 3 Soma dos int: 10 Outros: 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, "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}
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:
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}
um int; mais um dá 8 uma string de 2 bytes um valor verdadeiro/falso outro tipo: float64
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}
7 é int e volta do jeito que está; "hello" é string, então volta o tamanho, 5; 2.5 é float64, cai no default e dá -1.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.
número texto outro número
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}
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[]Shapepode 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.Printlnusa a interfacefmt.Stringer: se existir umString() string, ele chama.anyguarda qualquer coisa;v.(int)tira o valor e entra em pânico se você errar, enquanton, ok := v.(int)não.switch x := v.(type)trata cada tipo no seu próprio caso.