Go Arrays

In Go, arrays are designed to store multiple values of the same type within a single variable. This feature allows developers to work efficiently without the need for creating multiple variables for related data.

Tutorials dojo strip



How to Declare Arrays

Arrays in Go can be declared using two primary methods:

  1. Using the var keyword: var arrayName = [length]dataType{values} // Fixed length var arrayName = [...]dataType{values} // Length inferred
  2. Using shorthand with :=: arrayName := [length]dataType{values} // Fixed length arrayName := [...]dataType{values} // Length inferred

Note: The length of an array is always fixed in Go. It can be explicitly stated as a number or inferred automatically by the compiler based on the number of values.




Examples of Arrays in Go

Example 1: Declaring Arrays with Fixed Length

Go

Output:

Go


Example 2: Declaring Arrays with Inferred Length

Go

Output:

Go


Example 3: Array of Integers

Go

Output:

Go




Accessing Array Elements

To access a specific element in an array, simply use its index. Array indexing begins at 0.

Example:

Go

Output:

Go




Modifying Array Elements

It is also possible to change an element within an array by referring to its index.

Example:

Go

Output:

Go




Array Initialization Defaults

When an array or one of its elements is not explicitly initialized, Go assigns a default value based on the data type. For example, the default for integers is 0, and for strings, it is "".

Example:

Go

Output:

Go




Initializing Specific Elements Only

Go allows you to initialize specific elements in an array by specifying index-value pairs.

Example:

Go

Output:

Go




Finding the Array Length

The len() function is available to calculate the length of an array.

Example:

Go

Output:

Go

Tutorials dojo strip