Fundamentos de Go

Go Arrays

A fixed number of values of one type, and why assigning an array copies it.

  • Principiante
  • 2 min de lectura
  • 1 ejemplo ejecutable
Lo que aprenderás
  • [5]int and [...]int
  • Arrays are values
  • Arrays of arrays
var scores [5]int
720
01
02
03
644
Items you do not set keep the zero value.

Fixed size, copied on assignment

An array holds a fixed number of values of one type, and its length is part of its type. Arrays are less common than slices in Go, but slices are built on top of them.

[5]int starts with five zeros. [...] lets the compiler count the items. Assigning an array copies every item, so changing copyOfPrimes leaves primes alone. An array of arrays makes a grid.

Puntos clave

  1. The length is part of the type.
  2. Assigning an array copies every item.
  3. Slices are built on arrays.

Ejemplo ejecutable de Go

Go
Ejecutar código →
main.go
package main

import "fmt"

func main() {
	var scores [5]int // fixed size, zero values
	scores[0] = 72
	scores[4] = 64
	fmt.Println(scores, len(scores))

	primes := [...]int{2, 3, 5, 7}
	copyOfPrimes := primes // arrays are values: this copies all items
	copyOfPrimes[0] = 99
	fmt.Println(primes, copyOfPrimes)

	grid := [2][3]int{{1, 2, 3}, {4, 5, 6}}
	fmt.Println(grid[1][2], grid)
}
Obtén un botón Run para este ejemplo Resultado de ejecutar el código
[72 0 0 0 64] 5
[2 3 5 7] [99 3 5 7]
6 [[1 2 3] [4 5 6]]

Practica

Abre el ejemplo en el compilador online, cambia un valor o añade una línea y predice la salida antes de ejecutarlo. Después rompe el código a propósito y lee el mensaje del compilador.

¿Terminaste esta lección?

Márcala como aprendida para seguir tu progreso.

Siguiente: Slices →

Practica con un reto

Usa lo que cubre esta lección para resolver un problema real. Cada reto se ejecuta en el navegador, con pruebas al instante y una revisión de IA.

Todos los retos