Arrays have fixed size and limited flexibility. Knowing their limits helps you choose the right data structure.
0
0
Array limitations in Go
Introduction
When you know the exact number of items in advance.
When you need fast access to elements by index.
When memory usage must be predictable and fixed.
When you don't need to add or remove items after creation.
When you want simple, low-overhead storage for a small collection.
Syntax
Go
package main import "fmt" func main() { var fixedArray [5]int // Array with fixed size 5 fixedArray[0] = 10 // Assign value to first element fmt.Println(fixedArray) }
Arrays in Go have a fixed size that you set when you create them.
You cannot change the size of an array after it is created.
Examples
This creates an array with zero length. It holds no elements.
Go
var emptyArray [0]int fmt.Println(emptyArray)
An array with only one element. You can access it by index 0.
Go
var singleElementArray [1]string singleElementArray[0] = "hello" fmt.Println(singleElementArray)
An array fully initialized with three elements.
Go
var fullArray [3]int = [3]int{1, 2, 3} fmt.Println(fullArray)
Sample Program
This program shows that arrays have a fixed size of 3. You can assign values to existing indexes but cannot add more elements beyond size.
Go
package main import "fmt" func main() { // Create an array with fixed size 3 var numbers [3]int // Print initial state fmt.Println("Initial array:", numbers) // Assign values numbers[0] = 10 numbers[1] = 20 numbers[2] = 30 fmt.Println("After assigning values:", numbers) // Trying to add a new element beyond size causes error (uncomment to see compile error) // numbers[3] = 40 // Arrays cannot grow or shrink fmt.Println("Length of array:", len(numbers)) }
OutputSuccess
Important Notes
Time complexity for accessing elements by index is O(1).
Space complexity is fixed and depends on the array size.
Common mistake: Trying to add elements beyond the fixed size causes compile errors.
Use slices if you need dynamic size arrays that can grow or shrink.
Summary
Arrays have a fixed size set at creation and cannot change size later.
They provide fast access to elements by index but lack flexibility.
For flexible collections, use slices instead of arrays in Go.