typestar

Stringer en Go

Un método String cambia cómo fmt imprime tu tipo.

type Stars int

func (s Stars) String() string {
    if s < 0 || s > 3 {
        return "invalid"
    }
    return strings.Repeat("*", int(s)) + strings.Repeat(".", 3-int(s))
}

type Step struct {
    Title string
    Stars Stars
}

func (s Step) String() string {
    return fmt.Sprintf("%-12s %s", s.Title, s.Stars)
}

func show() string {
    return fmt.Sprint(Step{Title: "Slices", Stars: 2})
}

Cómo funciona

  1. fmt.Stringer es la interfaz de un método que fmt busca.
  2. Usa receptor por valor, o imprimir un valor no lo encontrará.
  3. Nunca llames fmt.Sprintf("%v", x) dentro de x.String().

Palabras clave y builtins usados aquí

El intento, en números

Líneas
21
Caracteres a escribir
362
Tokens
110
Ritmo de tres estrellas
105 tpm

Al ritmo de tres estrellas de 105 tokens por minuto, este intento toma unos 63 segundos.

Escribe este fragmento

Paso 2 de 3 en Interfaces estándar; paso 11 de 19 en Interfaces y genéricos.

← Anterior Siguiente →