Go — Slices
Creating slices
package main
import "fmt"
func main() {
// Literal
nums := []int{1, 2, 3, 4, 5}
// Make
s := make([]int, 5) // len=5, cap=5
s2 := make([]int, 0, 10) // len=0, cap=10
// From array
arr := [5]int{10, 20, 30, 40, 50}
slice := arr[1:4] // [20, 30, 40]
fmt.Println(nums, s, s2, slice)
}
Slice internals
A slice is a struct with three fields:
type slice struct {
array unsafe.Pointer // pointer to underlying array
len int
cap int
}
Append
s := []int{1, 2, 3}
s = append(s, 4, 5)
fmt.Println(s) // [1 2 3 4 5]
// Append slice
s2 := []int{6, 7}
s = append(s, s2...)
fmt.Println(s) // [1 2 3 4 5 6 7]
Copy
src := []int{1, 2, 3, 4, 5}
dst := make([]int, 3)
n := copy(dst, src)
fmt.Println(dst, n) // [1 2 3] 3
Delete elements
s := []int{1, 2, 3, 4, 5}
// Delete index 2
s = append(s[:2], s[3:]...)
fmt.Println(s) // [1 2 4 5]
// Delete range
s = append(s[:1], s[3:]...)
fmt.Println(s) // [1 4 5]
Common patterns
// Filter
nums := []int{1, 2, 3, 4, 5, 6}
var evens []int
for _, n := range nums {
if n%2 == 0 {
evens = append(evens, n)
}
}
// Map
doubled := make([]int, len(nums))
for i, n := range nums {
doubled[i] = n * 2
}
// Reverse
for i, j := 0, len(nums)-1; i < j; i, j = i+1, j-1 {
nums[i], nums[j] = nums[j], nums[i]
}
Mini Practice
Write Go code that:
- Creates a slice with
makeandappend - Uses
copyto duplicate a slice - Deletes an element without losing other elements
- Implements filter and map operations
Up Next
In the next lesson, you'll learn about Maps — key-value collections.
Related Topics
Frequently Asked Questions about Slices
What is Slices in Go?
Slices 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 Slices?
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 Slices.
Why is Slices important in Go?
Slices is essential for Go development. Understanding this concept will help you write better code and solve real-world problems more effectively.