typestar

Interfaces en Go

Satisfacción implícita: no hay palabra clave implements.

type Shape interface {
    Area() float64
    Name() string
}

type Rect struct{ W, H float64 }

func (r Rect) Area() float64 { return r.W * r.H }
func (r Rect) Name() string  { return "rect" }

func report(shapes []Shape) {
    for _, s := range shapes {
        fmt.Printf("%s: %.2f\n", s.Name(), s.Area())
    }
}

Cómo funciona

  1. Una interfaz lista las firmas de métodos requeridas.
  2. Rect satisface Shape con solo tenerlas.
  3. El código depende de la interfaz, no del tipo.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
15
Caracteres a escribir
292
Tokens
91
Ritmo de tres estrellas
100 tpm

Al ritmo de tres estrellas de 100 tokens por minuto, este intento toma unos 55 segundos.

Escribe este fragmento

Paso 1 de 4 en Interfaces; paso 4 de 19 en Interfaces y genéricos.

← Anterior Siguiente →

Interfaces en otros lenguajes