Slices vs ArraysBeginner
1Question 1 of 1
goWhat is the difference between Slices and Arrays in Go?
Explanation & Concept
• Arrays: Fixed-length, value types. The size is part of the type signature (`[5]int` is a different type than `[10]int`). Passing an array copies all its elements. • Slices: Dynamic, lightweight descriptors wrapping an underlying array. A slice consists of a pointer to the array, a length (`len`), and a capacity (`cap`).
Code Example
go
package main
import "fmt"
func main() {
// Slice literal
s := []int{10, 20, 30}
fmt.Printf("Len: %d, Cap: %d\n", len(s), cap(s))
// Append dynamically allocates larger backing array when capacity is exceeded
s = append(s, 40, 50)
fmt.Printf("After append: Len: %d, Cap: %d\n", len(s), cap(s))
}How It Works & Key Takeaways
Passing slices to functions is cheap because only the 24-byte slice header (pointer, length, capacity) is copied, not the underlying array.
Mock Test · 1 Questions · Optional
Ready for Defer, Panic & Recover?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner1 questions