Kodewick
Empieza a aprender →
Interfaces13 / 24

Interfaces en Go

Lección 13 de 24 · Parte 3 · Tipos · unos 15 minutos

Una interfaz enumera un conjunto de métodos, y cualquier tipo que tenga esos métodos la implementa automáticamente, sin ningún «implements»; las más comunes son fmt.Stringer y error.

Los rectángulos y los círculos tienen área, pero se calcula de formas distintas. Una interfaz describe lo que un valor sabe hacer: es un conjunto de métodos. Aquí Shape pide un método, Area() float64, y describe acepta cualquier valor que lo tenga:

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}
Salida
Área: 12.00
Área: 3.14

A describe no le importa si ha recibido un rectángulo o un círculo; ni siquiera lo sabe. Solo llama a Area.

«interface»Shape
  • Area() float64
structRect
  • Width, Height
  • +Area()
structCircle
  • Radius
  • +Area()
Rect y Circle tienen Area(), así que los dos implementan Shape; a describe solo le importa Shape
Elige una

¿Qué valores acepta describe(s Shape)?

Sin implements

Rect y Circle nunca dicen «soy un Shape». En Go, un tipo que tiene todos los métodos que pide una interfaz implementa esa interfaz automáticamente; no existe la palabra clave implements.

Una variable de tipo interfaz puede guardar cualquier valor que la implemente, y lo que guarda puede cambiar:

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}
Salida
10
12.57
main.Circle

%T muestra el tipo de lo que s guarda en ese momento: main.Circle (el Circle del paquete main).

Adivina la salidaFallar no pasa nada

¿Qué muestra este programa?

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 distintas en un mismo slice

Un []Shape puede guardar rectángulos y círculos uno al lado del otro. Un solo bucle suma sus á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}
Salida
Área total: 16.14

Si más adelante añades otra clase de forma (un triángulo), mientras tenga Area, este bucle no cambia nada.

Elige una

Más adelante añades un Triangle. ¿Qué cambias en el bucle que suma las áreas?

Ejercicio 1

Que el cuadrado también sea una forma

Este programa no compila: Square todavía no es un Shape. Dale a Square un método Area (lado por lado) para que el programa muestre el área de cada forma.

Debería 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}
Salida
Pulsa Ejecutar o Ctrl+Enter

Un método que falta

Un tipo al que le falta un método que pide la interfaz no se puede usar como esa interfaz. El compilador te dice qué método falta:

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}
Salida
# 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 no tiene método Area. Añade func (t Triangle) Area() float64 y compila.

Un caso más: cuando un método tiene receptor puntero, solo el puntero *Counter tiene ese método, no el propio 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}
Salida
# 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: lo que entra en la interfaz tiene que ser &c. Llamar directamente a c.Inc() no da problemas, porque Go toma la dirección de la variable por ti (lección 12); meter c en una interfaz no lo hace, así que escribes &c tú. Tiene sentido: si entrara una copia de c, Inc cambiaría la copia.

meter cvar i Incrementer = cerror de compilaciónCounter no tiene Inc
meter &cvar i Incrementer = &cfunciona*Counter sí tiene Inc
Inc tiene un receptor *Counter: en la interfaz hay que meter &c
Adivina la salidaFallar no pasa nada

¿Qué muestra esto?

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 qué funcionaba el método String de la lección 12? El paquete fmt tiene una interfaz:

type Stringer interface { String() string }

Cuando fmt.Println recibe un valor, primero comprueba si implementa fmt.Stringer; si lo hace, llama a String. Tus propias funciones también pueden aceptar un 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 años)", e.Name, e.Age)12}13 14func introduce(s fmt.Stringer) {15	fmt.Println("Te presento a " + s.String())16}17 18func main() {19	e := Employee{Name: "Maya", Age: 28}20	fmt.Println(e)21	introduce(e)22}
Salida
Maya (28 años)
Te presento a Maya (28 años)
«interface»Stringer
  • String() string
structEmployee
  • Name
  • Age
  • +String()
Employee tiene String() string, así que implementa fmt.Stringer, y fmt.Println lo llama
Adivina la salidaFallar no pasa nada

¿Qué muestra este programa?

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}

La interfaz vacía: any

Una interfaz que no pide ningún método es interface{}, y Go le da un nombre corto, any. Todos los tipos la implementan, así que una variable de tipo any puede guardar cualquier cosa:

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

Los parámetros de fmt.Println son any, y por eso puede mostrar cualquier cosa. Pero una vez que un valor está dentro de un any, Go solo sabe que «es un valor», así que no puedes sumarle nada directamente: primero tienes que volver a sacar el valor.

Adivina la salidaFallar no pasa nada

¿Qué muestra este programa?

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}

Aserciones de tipo

v.(int) es una aserción de tipo (en inglés, *type assertion*): dice «v guarda un int» y lo saca. Añade un ok para preguntar 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}
Salida
43
false true

v no guarda un string, así que ok es false y s es el valor cero "" (s == "" es true). Sin ok, si te equivocas, el programa entra en 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}
Salida
panic: interface conversion: interface {} is string, not int

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

Qué pasó: The type assertion failed: the interface holds a different type.

interface conversion: interface {} is string, not int: v guarda un string, no un int. (interface {} es any.) Cuando no estés seguro de lo que hay dentro, usa la forma con ok.

CompletaToca una para llenar un hueco; toca el hueco para quitarla

Elige un tipo para el hueco y que el programa muestre go true.

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

Suma solo los int

Termina sumInts: suma los int de values, cuenta cuántos no son int y devuelve las dos cosas. Usa una aserción de tipo con ok. El programa prueba dos grupos de valores.

Debería mostrar
Suma de los int: 20 Otros: 3
Suma de los int: 10 Otros: 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, "boli", 4.5, 7, true, 10})13	fmt.Println("Suma de los int:", sum, "Otros:", others)14	sum, others = sumInts([]any{"leche", 5, 5, 2.5})15	fmt.Println("Suma de los int:", sum, "Otros:", others)16}
Salida
Pulsa Ejecutar o Ctrl+Enter

Type switch

Para tratar cada tipo de forma distinta, usa un type switch. Con switch x := v.(type), dentro de cada case la variable x tiene el tipo de ese 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("un int; más uno da %d", x+1)9	case string:10		return fmt.Sprintf("un string de %d bytes", len(x))11	case bool:12		return "un valor verdadero/falso"13	default:14		return fmt.Sprintf("otro 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}
Salida
un int; más uno da 8
un string de 2 bytes
un valor verdadero/falso
otro tipo: float64
Adivina la salidaFallar no pasa nada

¿Qué muestra este programa?

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}
Ejercicio 3

¿Qué tipo hay dentro?

Termina kind: devuelve número si v guarda un int, texto si guarda un string y otro para cualquier otra cosa.

Debería mostrar
número
texto
otro
número
exercise3.go
1package main2 3import "fmt"4 5func kind(v any) string {6	return "otro"7}8 9func main() {10	for _, v := range []any{10, "manzana", 3.5, -2} {11		fmt.Println(kind(v))12	}13}
Salida
Pulsa Ejecutar o Ctrl+Enter

Lo que has aprendido

  • Una interfaz es un conjunto de métodos: type Shape interface { Area() float64 }.
  • Un tipo con todos esos métodos implementa la interfaz automáticamente, sin implements; un []Shape puede guardar tipos distintos.
  • Un método que falta es un error de compilación, does not implement … (missing method …); con métodos de receptor puntero, mete &c.
  • fmt.Println usa la interfaz fmt.Stringer: si hay un String() string, lo llama.
  • any guarda cualquier cosa; v.(int) saca el valor y entra en pánico si te equivocas, mientras que n, ok := v.(int) no.
  • switch x := v.(type) trata cada tipo en su propio caso.
¿Terminaste la lección 13?Lección 13 de 24 · el progreso se queda en este navegador
Siguiente · lección 14 · 15 minErroresGestiona los errores al estilo de Go: resultados (valor, error), if err != nil, errors.New, fmt.Errorf y %w, errors.Is y errors.As, y tus propios tipos de error.Siguiente lección →
El botón marca esta lección como hecha y abre la siguiente.