typestar

Opciones funcionales en Go

La respuesta de Go a los argumentos opcionales: variádicas que mutan una config.

type Server struct {
    addr    string
    timeout time.Duration
    verbose bool
}

type Option func(*Server)

func WithTimeout(d time.Duration) Option {
    return func(s *Server) { s.timeout = d }
}

func WithVerbose() Option {
    return func(s *Server) { s.verbose = true }
}

func NewServer(addr string, options ...Option) *Server {
    server := &Server{addr: addr, timeout: 30 * time.Second}
    for _, apply := range options {
        apply(server)
    }
    return server
}

func configured() string {
    s := NewServer(":8080", WithTimeout(time.Second), WithVerbose())
    return fmt.Sprintf("%s %s %t", s.addr, s.timeout, s.verbose)
}

Cómo funciona

  1. Cada opción es una función que edita el struct.
  2. El constructor aplica los valores por defecto y luego las opciones.
  3. Agregar una opción después no rompe a ningún llamador existente.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
28
Caracteres a escribir
596
Tokens
155
Ritmo de tres estrellas
110 tpm

Al ritmo de tres estrellas de 110 tokens por minuto, este intento toma unos 85 segundos.

Escribe este fragmento

Paso 1 de 2 en Formas de API; paso 17 de 19 en Interfaces y genéricos.

← Anterior Siguiente →