0
0
Goprogramming~15 mins

Array declaration in Go - Deep Dive

Choose your learning style9 modes available
Overview - Array declaration
What is it?
An array in Go is a collection of elements of the same type stored in a fixed-size sequence. You declare an array by specifying its size and the type of elements it will hold. Once created, the size of an array cannot change. Arrays help organize multiple values under a single name for easy access and management.
Why it matters
Arrays exist to group related data together in a structured way, making it easier to manage and process multiple values. Without arrays, you would need separate variables for each value, which is inefficient and error-prone. Arrays enable programs to handle lists of data, like scores, names, or measurements, in a clean and organized manner.
Where it fits
Before learning arrays, you should understand basic variables and data types in Go. After arrays, you can learn about slices, which are more flexible and commonly used for dynamic collections. Arrays are the foundation for understanding how Go handles collections of data.
Mental Model
Core Idea
An array is like a row of fixed-size mailboxes, each holding one item of the same type, accessed by their position number.
Think of it like...
Imagine a row of identical mailboxes, each labeled with a number. You can put one letter in each mailbox, and you always know which mailbox to open by its number. The mailboxes are fixed in number and size, just like an array's elements.
Array structure:
┌─────┬─────┬─────┬─────┐
│ [0] │ [1] │ [2] │ [3] │  ... indexes
├─────┼─────┼─────┼─────┤
│ val │ val │ val │ val │  values
└─────┴─────┴─────┴─────┘
Build-Up - 6 Steps
1
FoundationBasic array declaration syntax
🤔
Concept: How to declare an array with a fixed size and type in Go.
In Go, you declare an array by specifying the size in square brackets and the type of elements. For example: var numbers [5]int This creates an array named 'numbers' that can hold 5 integers. All elements start with the zero value for the type, here 0 for int.
Result
An array 'numbers' of 5 integers is created, all initialized to 0.
Understanding the syntax is the first step to using arrays; the fixed size and type are key characteristics.
2
FoundationAccessing and modifying array elements
🤔
Concept: How to read and change values at specific positions in an array.
You access array elements by their index, starting at 0. For example: numbers[0] = 10 fmt.Println(numbers[0]) This sets the first element to 10 and prints it. You can change any element by its index.
Result
The first element of 'numbers' is set to 10 and printed as 10.
Knowing how to access elements by index lets you work with individual data points inside the array.
3
IntermediateArray initialization with values
🤔Before reading on: do you think you can declare and set array values in one line? Commit to your answer.
Concept: How to declare an array and assign values at the same time.
You can declare and initialize an array in one line using curly braces: var primes = [5]int{2, 3, 5, 7, 11} This creates an array 'primes' with 5 integers already set to those values.
Result
An array 'primes' with values 2, 3, 5, 7, 11 is created.
Combining declaration and initialization saves code and makes arrays ready to use immediately.
4
IntermediateArray length and type inference
🤔Before reading on: do you think Go can figure out the array size automatically? Commit to your answer.
Concept: Using '...' to let Go infer the array size from the number of values provided.
Instead of specifying the size, you can use '...' and let Go count the elements: var letters = [...]string{"a", "b", "c"} Go creates an array of size 3 automatically.
Result
An array 'letters' of 3 strings is created with values "a", "b", "c".
Letting Go infer size reduces errors and makes code cleaner when you know the values upfront.
5
AdvancedArrays are value types in Go
🤔Before reading on: do you think assigning one array to another copies the data or shares it? Commit to your answer.
Concept: Understanding that arrays are copied when assigned or passed to functions, not referenced.
In Go, arrays are value types. When you assign one array to another, a full copy is made: var a = [3]int{1, 2, 3} var b = a b[0] = 100 fmt.Println(a[0]) // prints 1 Changing 'b' does not affect 'a'.
Result
The original array 'a' remains unchanged after modifying 'b'.
Knowing arrays copy on assignment prevents bugs related to unexpected shared changes.
6
ExpertArrays vs slices: internal differences
🤔Before reading on: do you think arrays and slices behave the same in memory and performance? Commit to your answer.
Concept: How arrays differ from slices internally and why slices are preferred for flexible collections.
Arrays have fixed size and store data inline. Slices are descriptors pointing to arrays with length and capacity, allowing dynamic resizing. Arrays copy data on assignment; slices copy descriptors only. This makes slices more efficient and flexible for most uses.
Result
Understanding the difference explains why slices are used more often than arrays in Go programs.
Recognizing arrays as fixed, copied values and slices as flexible views clarifies Go's collection design and performance.
Under the Hood
Arrays in Go allocate a contiguous block of memory sized to hold all elements. Each element occupies space according to its type. When you assign an array, Go copies the entire block to a new memory location. Accessing elements uses pointer arithmetic to find the correct offset from the array's base address.
Why designed this way?
Go arrays are designed as value types to ensure safety and simplicity. Copying arrays prevents unintended side effects from shared data, which is important in concurrent programming. Fixed size arrays simplify memory management and improve performance predictability. Slices were introduced later to provide flexibility without sacrificing safety.
Memory layout of array:

Base address -> [ elem0 ][ elem1 ][ elem2 ] ... [ elemN ]

Assignment copies entire block:

[ a ] ----copy----> [ b ] (separate memory)

Access:

address_of_array + (index * size_of_element) = element_address
Myth Busters - 4 Common Misconceptions
Quick: Does assigning one array to another share the same data or copy it? Commit to your answer.
Common Belief:Assigning one array to another creates a shared reference to the same data.
Tap to reveal reality
Reality:Assigning arrays copies all elements to a new array; they do not share data.
Why it matters:Assuming shared data can cause bugs where changes to one array unexpectedly affect another.
Quick: Can you change the size of an array after declaration? Commit to your answer.
Common Belief:Arrays in Go can be resized dynamically like lists in other languages.
Tap to reveal reality
Reality:Arrays have a fixed size that cannot be changed after declaration.
Why it matters:Trying to resize arrays leads to errors; slices should be used for dynamic collections.
Quick: Does using '...' in array declaration create a slice or an array? Commit to your answer.
Common Belief:Using '...' creates a slice with dynamic size.
Tap to reveal reality
Reality:Using '...' creates an array with size inferred from the number of elements.
Why it matters:Confusing arrays and slices can cause unexpected behavior and inefficient code.
Quick: Are arrays the most common way to handle collections in Go? Commit to your answer.
Common Belief:Arrays are the primary and most flexible way to handle collections in Go.
Tap to reveal reality
Reality:Slices are more commonly used because they are flexible and efficient; arrays are less common.
Why it matters:Overusing arrays can lead to rigid and less efficient code compared to slices.
Expert Zone
1
Arrays being value types means passing them to functions copies data, which can be costly for large arrays; pointers or slices are preferred in such cases.
2
The array size is part of its type, so [3]int and [4]int are different types, affecting function signatures and assignments.
3
Arrays can be multidimensional, but each dimension's size is fixed and part of the type, which influences memory layout and performance.
When NOT to use
Avoid arrays when you need collections that change size or when passing large data around; use slices instead. For very large fixed-size data, arrays can be efficient, but slices with backing arrays offer more flexibility.
Production Patterns
In production Go code, arrays are mostly used for fixed-size buffers or constants. Slices dominate for general collections. Arrays appear in performance-critical code where fixed size and memory layout matter, such as cryptography or graphics.
Connections
Slices in Go
Slices build on arrays by adding dynamic size and flexible views over arrays.
Understanding arrays clarifies how slices work internally as descriptors pointing to arrays, explaining their behavior and performance.
Memory management
Arrays illustrate contiguous memory allocation and copying semantics in Go.
Knowing how arrays occupy memory helps understand performance implications and why copying large arrays can be costly.
Data structures in computer science
Arrays are a fundamental data structure used across programming languages and systems.
Recognizing arrays as fixed-size, indexed collections connects Go programming to universal computing concepts.
Common Pitfalls
#1Trying to resize an array after declaration.
Wrong approach:var a [3]int a = append(a, 4) // error: append not defined for arrays
Correct approach:var s []int = []int{1, 2, 3} s = append(s, 4) // works with slices
Root cause:Misunderstanding that arrays have fixed size and append works only with slices.
#2Assuming arrays are reference types and modifying a copy affects the original.
Wrong approach:var a = [3]int{1, 2, 3} var b = a b[0] = 100 fmt.Println(a[0]) // expecting 100 but prints 1
Correct approach:Use pointers or slices to share data: var a = [3]int{1, 2, 3} var b = &a (*b)[0] = 100 fmt.Println(a[0]) // prints 100
Root cause:Not knowing arrays are copied on assignment, so changes to the copy don't affect the original.
#3Confusing array type sizes causing assignment errors.
Wrong approach:var a [3]int var b [4]int a = b // compile error: mismatched types
Correct approach:Ensure arrays have the same size: var a [3]int var b [3]int a = b // works
Root cause:Not realizing array size is part of the type, so different sizes mean different types.
Key Takeaways
Arrays in Go are fixed-size collections of elements of the same type, declared with size and type.
Arrays are value types, so assigning or passing them copies all elements, not references.
You cannot resize arrays; for flexible collections, use slices which build on arrays.
The array size is part of its type, affecting assignments and function parameters.
Understanding arrays helps grasp Go's memory model and why slices are preferred in most cases.