Go — Arrays
Arrays
Fixed-size collections:
package main
import "fmt"
func main() {
var arr [5]int
arr[0] = 10
arr[1] = 20
fruits := [3]string{"Apple", "Banana", "Cherry"}
fmt.Println(arr) // [10 20 0 0 0]
fmt.Println(fruits) // [Apple Banana Cherry]
fmt.Println(len(arr)) // 5
}
Array operations
a := [3]int{1, 2, 3}
b := [3]int{4, 5, 6}
// Copy (arrays are value types)
c := a
c[0] = 100
fmt.Println(a) // [1 2 3] (unchanged)
fmt.Println(c) // [100 2 3]
// Compare
fmt.Println(a == b) // false
Slices
Dynamic-length views of arrays:
nums := []int{1, 2, 3, 4, 5}
slice := nums[1:3] // [2, 3]
fmt.Println(nums) // [1 2 3 4 5]
fmt.Println(slice) // [2 3]
// Append
nums = append(nums, 6, 7)
// Make
data := make([]int, 5, 10) // len=5, cap=10
Slice operations
s := []int{1, 2, 3, 4, 5}
// Subslice
sub := s[1:3] // [2, 3]
// Copy
dst := make([]int, 3)
copy(dst, s[:3])
// Delete
s = append(s[:2], s[3:]...) // Remove index 2
// Reverse
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
Multi-dimensional arrays
matrix := [3][4]int{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
}
fmt.Println(matrix[1][2]) // 7
Best practices
- Use slices over arrays in most cases
- Use
maketo pre-allocate when size is known - Use
appendto grow slices dynamically - Be aware that slices share underlying arrays
Mini Practice
Write Go code that:
- Creates a slice and appends elements
- Uses
copyto duplicate a slice - Deletes an element from a slice
- Creates a multi-dimensional array
Up Next
In the next lesson, you'll learn about Slices — Go's dynamic arrays in depth.
Related Topics
Frequently Asked Questions about Arrays
What is Arrays in Go?
Arrays is a fundamental concept in Go. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Arrays?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Arrays.
Why is Arrays important in Go?
Arrays is essential for Go development. Understanding this concept will help you write better code and solve real-world problems more effectively.