0
0
GoHow-ToBeginner · 3 min read

How to Create Array in Go: Syntax and Examples

In Go, you create an array using the syntax var name [size]type, where size is the fixed length and type is the data type. You can also initialize an array with values using name := [size]type{values}.
📐

Syntax

An array in Go is a fixed-size collection of elements of the same type. The syntax to declare an array is:

  • var name [size]type: declares an array named name with size elements of type.
  • name := [size]type{values}: declares and initializes the array with values.

The size must be a constant and defines the number of elements the array can hold.

go
var arr [5]int
arr2 := [3]string{"a", "b", "c"}
💻

Example

This example shows how to declare an array of integers, assign values, and print them.

go
package main

import "fmt"

func main() {
    var numbers [4]int
    numbers[0] = 10
    numbers[1] = 20
    numbers[2] = 30
    numbers[3] = 40

    fmt.Println("Array elements:")
    for i, v := range numbers {
        fmt.Printf("Index %d: %d\n", i, v)
    }

    // Declare and initialize in one line
    letters := [3]string{"x", "y", "z"}
    fmt.Println("Letters array:", letters)
}
Output
Array elements: Index 0: 10 Index 1: 20 Index 2: 30 Index 3: 40 Letters array: [x y z]
⚠️

Common Pitfalls

Common mistakes when creating arrays in Go include:

  • Trying to change the size of an array after declaration (arrays have fixed size).
  • Confusing arrays with slices (slices are dynamic, arrays are not).
  • Not initializing all elements, which defaults to zero values but might cause confusion.

Example of wrong and right ways:

go
package main

import "fmt"

func main() {
    // Wrong: Trying to append to an array (does not work)
    arr := [3]int{1, 2, 3}
    // arr = append(arr, 4) // This causes a compile error

    // Right: Use a slice for dynamic size
    slice := []int{1, 2, 3}
    slice = append(slice, 4)
    fmt.Println("Slice after append:", slice)
}
Output
Slice after append: [1 2 3 4]
📊

Quick Reference

ConceptSyntaxDescription
Declare arrayvar arr [size]typeCreates an array with fixed size and type
Initialize arrayarr := [size]type{values}Creates and fills array with values
Access elementarr[index]Gets or sets element at position index
Array lengthlen(arr)Returns the number of elements
Arrays are fixed sizeCannot change size after declarationUse slices for dynamic arrays

Key Takeaways

Arrays in Go have a fixed size defined at declaration and cannot be resized.
Use the syntax var name [size]type or name := [size]type{values} to create arrays.
Arrays hold elements of the same type and default to zero values if not initialized.
To work with dynamic collections, use slices instead of arrays.
Access array elements using zero-based indexing with arr[index].