Go Arrays

Go Arrays

Kishore V


Go Arrays

In Go, an array is a data structure used to store multiple values of the same type in a single variable. Instead of creating separate variables for each value, arrays allow you to manage collections of data efficiently.

What Is an Array?

An array:

  • Holds a fixed number of elements
  • Stores elements of the same data type
  • Uses index-based access (starting from 0)

Important: The size of an array in Go is fixed once declared and cannot be changed.

Declaring Arrays in Go

There are two common ways to declare arrays:

1. Using var

var scores = [4]int{85, 90, 78, 92}

2. Using Short Declaration (:=)

marks := [3]int{70, 80, 95}

Letting Go Infer Array Length

You can allow the compiler to determine the array size using ....

Prime numbers: [2 3 5 7 11]

Working with Arrays

Example: Declaring and Printing Arrays

Temperatures: [36.5 37 36.8] Cities: [Chennai Delhi Mumbai]

Accessing Array Elements

Array elements are accessed using their index.

First price: 100 Last price: 400

Modifying Array Elements

You can update elements by assigning a new value to a specific index.

Updated stock: [10 50 30]

Array Initialization and Default Values

If elements are not initialized, Go assigns default values:

  • int0
  • string""
  • boolfalse
Numbers: [0 0 0 0 0] Partial: [1 2 3 0 0]

Initializing Specific Elements

You can initialize selected indices directly.

Custom array: [10 0 0 40 0]

Explanation:

  • Index 0 → 10
  • Index 3 → 40
  • Other elements default to 0

Finding the Length of an Array

Use the built-in len() function to get the number of elements.

Number of languages: 3


Our website uses cookies to enhance your experience. Learn More
Accept !