typestar

Punteros en Go

Go tiene punteros pero sin aritmética: existen para compartir y para mutar.

type Counter struct {
    n int
}

func (c *Counter) Add(delta int) { c.n += delta }
func (c Counter) Value() int     { return c.n }

func pointers() (int, int, bool) {
    counter := Counter{}
    counter.Add(3) // Go toma la dirección por ti
    byPointer := &counter
    byPointer.Add(4)

    fresh := new(int)
    *fresh = 7

    var nothing *Counter
    return counter.Value(), *fresh, nothing == nil
}

Cómo funciona

  1. &x toma una dirección; *p lee a través de él.
  2. new(T) asigna un T en cero y devuelve su puntero.
  3. Desreferenciar un puntero nil hace panic; revisa cuando pueda serlo.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
19
Caracteres a escribir
371
Tokens
102
Ritmo de tres estrellas
80 tpm

Al ritmo de tres estrellas de 80 tokens por minuto, este intento toma unos 76 segundos.

Escribe este fragmento

Paso 5 de 5 en Variables y tipos; paso 5 de 30 en Fundamentos del lenguaje.

← Anterior Siguiente →