A slice is a dynamically-sized, flexible view into the elements of an array. Unlike arrays, you don't need to know the length at compile time.
arr := [5]int{10, 20, 30, 40, 50}
slice := arr[1:4] // elements 20, 30, 40You can create slices directly or from arrays:
Unlike arrays, slices can grow dynamically with append.
Use append() to grow a slice:
s := []int{1, 2}
s = append(s, 3, 4) // [1, 2, 3, 4]You can also append another slice:
A slice has both len() and cap():
Capacity is the total space allocated; length is how many elements are initialized.
Slices share the same underlying array. Modifying one affects others if they overlap:
Use the built-in copy function to avoid shared memory:
original := []int{1, 2, 3}
copyTo := make([]int, len(original))
copy(copyTo, original)A nil slice has no underlying array; an empty slice has zero length but exists.
var a []int // nil
b := []int{} // emptyUse len() or compare to nil to check.
Ask the AI if you need help understanding or want to dive deeper in any topic