Golang Tutorial
Fundamentals
Control Statements
Functions & Methods
Structure
Arrays & Slices
String
Pointers
Interfaces
Concurrency
Slices are a key data structure in Go, offering a more flexible alternative to arrays. They are essentially a view into an underlying array, providing dynamic-sized, flexible views into the segments of those arrays. This tutorial will guide you through the essentials of working with slices in Go.
A slice doesn't store any data itself; it describes a section of an underlying array.
package main import "fmt" func main() { // Zero value of a slice is nil var s []int fmt.Println(s, len(s), cap(s)) // [] 0 0 // Creating a slice using make s = make([]int, 5) // Length is 5, capacity is 5 fmt.Println(s) // [0 0 0 0 0] // Creating a slice using a composite literal t := []int{1, 2, 3, 4, 5} fmt.Println(t) // [1 2 3 4 5] }
A slice has both a length and a capacity:
len
): The current number of elements in the slice.cap
): The total number of elements the underlying array can accommodate.s := []int{1, 2, 3, 4, 5} fmt.Println(len(s)) // 5 fmt.Println(cap(s)) // 5
You can create a new slice from an existing slice by specifying a range.
s := []int{1, 2, 3, 4, 5} sub := s[1:4] // Slice from index 1 (inclusive) to 4 (exclusive) fmt.Println(sub) // [2 3 4]
Slices are references to the underlying array. Modifying an element of a slice changes the content of the underlying array.
s := []int{1, 2, 3} s[1] = 10 fmt.Println(s) // [1 10 3]
You can add new elements to a slice using the append
function. If the underlying array is too small to fit the new values, append
will allocate a new, larger array.
s := []int{1, 2, 3} s = append(s, 4, 5, 6) fmt.Println(s) // [1 2 3 4 5 6]
Use the range
keyword with a for
loop to iterate over slices.
s := []int{1, 2, 3, 4, 5} for index, value := range s { fmt.Printf("Index: %d, Value: %d\n", index, value) }
You can copy one slice into another using the copy
function.
src := []int{1, 2, 3, 4, 5} dst := make([]int, 5) copy(dst, src) fmt.Println(dst) // [1 2 3 4 5]
While Go doesn't support true multidimensional arrays or slices, you can define an array of arrays or a slice of slices.
matrix := [][]int{ {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, } fmt.Println(matrix) // [[1 2 3] [4 5 6] [7 8 9]]
append
and copy
help in managing slices.Once you grasp the concept of slices and their relationship to arrays, you'll find that they are a powerful and essential tool in Go programming.
Creating and initializing slices in Golang:
Slices in Go are created by specifying a range of elements from an array or another slice.
package main import "fmt" func main() { // Creating and initializing slices numbers := []int{1, 2, 3, 4, 5} fmt.Println(numbers) }
Working with slice operations in Golang:
Slices support various operations, such as accessing elements, finding the length and capacity, and checking equality.
slice := []int{1, 2, 3, 4, 5} fmt.Println("Length:", len(slice)) fmt.Println("Capacity:", cap(slice)) fmt.Println("First element:", slice[0])
Appending and deleting elements in Golang slices:
The append()
function is used to add elements to a slice. Deleting elements involves creating a new slice without the undesired elements.
// Appending elements numbers := []int{1, 2, 3} numbers = append(numbers, 4, 5) // Deleting elements indexToDelete := 2 numbers = append(numbers[:indexToDelete], numbers[indexToDelete+1:]...)
Slicing arrays and other slices in Golang:
Slicing allows you to create new slices from existing arrays or slices.
array := [5]int{1, 2, 3, 4, 5} slice := array[1:4] // Slicing an array originalSlice := []int{1, 2, 3, 4, 5} newSlice := originalSlice[1:4] // Slicing a slice
Resizing and reshaping slices in Golang:
You can resize a slice by creating a new slice with a different length. Reshaping involves changing the slice's capacity.
originalSlice := []int{1, 2, 3, 4, 5} resizedSlice := originalSlice[:3] // Resizing
Using make() function for slices in Golang:
The make()
function is used to create slices with a specified length and capacity.
// Creating a slice with make() numbers := make([]int, 3, 5)
Handling nil slices and zero-length slices in Golang:
A nil slice has a length and capacity of 0 and no underlying array. A zero-length slice is a valid slice with an underlying array.
// Nil slice var nilSlice []int // Zero-length slice zeroLengthSlice := []int{}