Sobes.tech
Junior — Middle

How is the array structure organized in memory and how is access to its elements performed?

sobes.tech AI

Answer from AI

In Go, arrays are contiguous blocks of memory where elements are stored one after another. Each element occupies a fixed size, depending on the data type.

Access to an array element is done through address calculation: the base address of the array plus an offset equal to the element's index multiplied by the size of the element. This provides quick access to any element by index in constant time.

Example:

var arr [5]int = [5]int{10, 20, 30, 40, 50}
// arr is stored in memory as a sequence of 5 integers
fmt.Println(arr[2]) // Will output 30

Here, arr[2] is the element with index 2, whose address is calculated as the start address of the array plus 2 * sizeof(int).