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
- Una interfaz lista las firmas de métodos requeridas.
RectsatisfaceShapecon solo tenerlas.- El código depende de la interfaz, no del tipo.
Palabras clave y builtins usados aquí
float64forfuncinterfacerangereturnstringstructtype
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.
Paso 1 de 4 en Interfaces; paso 4 de 19 en Interfaces y genéricos.