golang array syntax

Go Array Syntax

In Go, arrays are fixed-size sequences of elements of the same type. The syntax for declaring and initializing an array in Go is as follows:

var arrayName [size]elementType
  • arrayName is the name of the array.
  • size is the number of elements the array can hold.
  • elementType is the type of the elements in the array.

For example, to declare an array named numbers that can hold 5 integers, the syntax would be:

var numbers [5]int

This declares an array named numbers with a size of 5 and elements of type int.

To initialize the elements of an array, you can use an initializer list enclosed in curly braces {}. The number of elements in the initializer list must match the size of the array. For example:

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

This initializes the numbers array with the values 1, 2, 3, 4, and 5.

Alternatively, you can omit the size of the array and let Go infer it from the number of elements in the initializer list. For example:

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

This is equivalent to the previous example.

You can access individual elements of an array using the array name followed by the index enclosed in square brackets []. The index starts from 0 for the first element and goes up to size-1. For example:

fmt.Println(numbers[0]) // Output: 1
fmt.Println(numbers[2]) // Output: 3

You can also modify the value of an element by assigning a new value to it. For example:

numbers[1] = 10
fmt.Println(numbers[1]) // Output: 10

Arrays in Go are passed by value, which means that when you pass an array to a function, a copy of the array is made. If you modify the array within the function, the original array remains unchanged.

Arrays in Go have a fixed size, which means that once an array is declared, its size cannot be changed. If you need a collection with a variable size, you can use slices instead.

That's the basic syntax for arrays in Go. Let me know if you have any further questions.