Interfaces en Go
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:
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
A describe no le importa si ha recibido un rectángulo o un círculo; ni siquiera lo sabe. Solo llama a Area.
Area() float64
Width, Height
- +
Area()
Radius
- +
Area()
¿Qué valores acepta describe(s Shape)?
describe solo llama a Area, así que lo único que pide es ese método. En Go ni siquiera existe la palabra implements.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:
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 muestra el tipo de lo que s guarda en ese momento: main.Circle (el Circle del paquete main).
¿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}
s es un Rect: su área es 2 × 5 = 10. %T muestra el tipo que s guarda en ese momento, no Shape.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:
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
Si más adelante añades otra clase de forma (un triángulo), mientras tenga Area, este bucle no cambia nada.
Más adelante añades un Triangle. ¿Qué cambias en el bucle que suma las áreas?
s.Area() y le da igual qué forma haya en s. Un tipo nuevo con Area cabe en un []Shape y el bucle sigue funcionando.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.
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}
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:
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 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:
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: 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.
var i Incrementer = cerror de compilaciónCounter no tiene Incvar i Incrementer = &cfunciona*Counter sí tiene Inc¿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}
i guarda un puntero a c, así que i.Inc() cambia c. Se llama dos veces, así que la respuesta es 2.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:
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}
Maya (28 años) Te presento a Maya (28 años)
String() string
NameAge
- +
String()
¿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}
Point tiene String() string, así que fmt.Println lo llama y muestra (3, 4). Sin ese método verías {3 4}.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:
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}
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.
¿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}
%T muestra el tipo del valor que hay dentro del any: 1 es un int, "a" un string y true un bool.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:
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 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:
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 2Qué 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.
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}
v guarda un string, así que la aserción v.(string) acierta: s es "go" y ok es true. Con int saldría 0 false.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.
Suma de los int: 20 Otros: 3 Suma de los int: 10 Otros: 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, "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}
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:
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}
un int; más uno da 8 un string de 2 bytes un valor verdadero/falso otro tipo: float64
¿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}
7 es un int y se devuelve tal cual; "hello" es un string, así que sale su longitud, 5; 2.5 es un float64, cae en default y da -1.¿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.
número texto otro número
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}
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[]Shapepuede 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.Printlnusa la interfazfmt.Stringer: si hay unString() string, lo llama.anyguarda cualquier cosa;v.(int)saca el valor y entra en pánico si te equivocas, mientras quen, ok := v.(int)no.switch x := v.(type)trata cada tipo en su propio caso.