Go Arrays

In Go, an array is a collection of elements of the same type, stored in contiguous memory locations. The size of an array is fixed and specified at the time of its creation. Once an array is created, its size cannot be changed.

The syntax for creating an array in Go is as follows:

var arrayName [size]dataType
S‮uo‬rce:www.theitroad.com

Here's an example of creating an array of integers in Go:

var numbers [5]int

In this example, an array named numbers is created with a size of 5 and element type of int. The elements of the array are initialized to their default value, which is 0 in this case.

You can also initialize an array with values when it is created, like this:

var numbers [5]int = [5]int{1, 2, 3, 4, 5}

In this example, the array numbers is created and initialized with the values 1, 2, 3, 4, and 5.

You can also create an array without specifying its size explicitly, like this:

numbers := [...]int{1, 2, 3, 4, 5}

In this example, an array named numbers is created and initialized with the values 1, 2, 3, 4, and 5. The size of the array is inferred from the number of elements in the initializer.

To access an element of an array, you can use its index, which starts at 0. Here's an example:

fmt.Println(numbers[2])

In this example, the third element of the numbers array (which has an index of 2) is printed to the console.

You can also change the value of an element of an array by assigning a new value to it. Here's an example:

numbers[2] = 10

In this example, the value of the third element of the numbers array is changed from 3 to 10.