Hey there! ๐ Today weโre diving into arrays and slices in Go. Donโt worryโitโs easier than assembling IKEA furniture. Letโs break it down!
Arrays: The Strict Lunchbox ๐ฑ
Arrays are like a lunchbox with fixed compartments.
You declare how many slots it has upfront:
// A lunchbox with 5 sandwich slots (zero if empty)
lunchbox := [5]int{1, 2, 3, 4, 5}
Key quirks:
- Size is part of its type.
[5]int
โ[4]int
(Go wonโt let you mix them). - Rigid. No extra sandwiches allowed. ๐ค
Slices: The Flexible Backpack ๐
Slices are dynamicโlike a backpack that grows as you stuff more in:
// A backpack with sandwiches (size adjusts automatically!)
backpack := []int{1, 2, 3}
Why slices rule:
- โ No fixed size
- โ
Can
append()
more items - โ
Can slice parts (e.g.,
backpack[1:]
gives everything except the first item)
Letโs TDD a Sum Function โ
Step 1: Write the Test First ๐งช
func TestSum(t *testing.T) {
numbers := []int{1, 2, 3}
got := Sum(numbers)
want := 6
if got != want {
t.Errorf("got %d want %d (numbers: %v)", got, want, numbers)
}
}
Step 2: Make It Pass ๐โโ๏ธ
func Sum(numbers []int) int {
sum := 0
for _, num := range numbers { // _ ignores the index
sum += num
}
return sum
}
Boom! Test passes. ๐
SumAll: Sum Multiple Slices ๐ข
What if we want to sum multiple slices?
Test:
func TestSumAll(t *testing.T) {
got := SumAll([]int{1, 2}, []int{0, 9})
want := []int{3, 9}
if !reflect.DeepEqual(got, want) { // Slices canโt use ==
t.Errorf("got %v want %v", got, want)
}
}
Solution:
func SumAll(slices ...[]int) []int {
var sums []int
for _, slice := range slices {
sums = append(sums, Sum(slice))
}
return sums
}
Pro Tip: ...[]int
means โaccept any number of slices.โ
SumAllTails: Ignore the First Item ๐ซ๐
Sometimes you just want the tail (everything except the first element).
Test:
func TestSumAllTails(t *testing.T) {
t.Run("normal slices", func(t *testing.T) {
got := SumAllTails([]int{1, 2}, []int{0, 9})
want := []int{2, 9}
checkSums(t, got, want)
})
t.Run("empty slices", func(t *testing.T) {
got := SumAllTails([]int{}, []int{3, 4, 5})
want := []int{0, 9}
checkSums(t, got, want)
})
}
Solution:
func SumAllTails(slices ...[]int) []int {
var sums []int
for _, slice := range slices {
if len(slice) == 0 {
sums = append(sums, 0)
} else {
tail := slice[1:] // Take everything from index 1 onward
sums = append(sums, Sum(tail))
}
}
return sums
}
Watch out! Slicing an empty slice crashes. Always check len()
first.
Key Takeaways ๐๏ธ
- Arrays = Fixed size (
[5]int
). - Slices = Dynamic (
[]int
). Useappend()
to grow. - Slicing =
slice[low:high]
(e.g.,slice[1:]
= everything after index 0). reflect.DeepEqual
= Compares slices (but use carefullyโitโs not type-safe!).- Always handle empty slicesโor risk runtime panics!
Now go forth and slice like a pro! ๐๐ช
Next Up: Structs, methods & interfaces โ where Go gets really fun. ๐