Page Content

Tutorials

What Is Mean By Slice In Go Explained With Code Examples

Slice in Go

A slice, which is a chunk of an array in Go, is a more useful and popular data type than a raw array. Slices are dynamic, meaning their length can vary, whereas arrays have a set length that is decided upon at formation. Like arrays, they are indexable and function as a “window” or “view” into an underlying array. This implies that changing components via a slice immediately modifies the array underneath.

Definition and Characteristics

Dynamic Length: In contrast to arrays, a slice’s length is not fixed and is subject to vary. If the system’s memory capacity is inadequate, a slice will ask for additional when new items are added.

Underlying Array: There is always an underlying array that each slice “points to” or is connected to. Although it can be smaller, a slice can never be longer than the array it is based on.

Indexing: Like arrays, the elements in a slice are accessed with square brackets [] and an index that starts at 0. There will be a runtime panic if you try to access an index outside of the slice’s defined range.

Pass by Reference (Implicit): A slice’s memory address is supplied as an input to a function instead of a complete copy of its contents. This enables changes made to the function’s slice to have an impact on the original underlying array.

Declaration and Initialization

Slices can be initialized and declared in a number of ways:

Declaring a nil slice: Consequently, a slice of length 0 is produced. If a slice is declared without the make built-in or a composite literal, its value will be nil.

With nil slices, you can use the range keyword, len built-in, and append built-in.

Using make() function: You can specify the length and capacity of slices using the make function, which is the recommended method.

  • length: The quantity of items that are presently visible through the slice.
  • capacity: How much space in the underlying array has been set aside for the slice overall. The capacity argument takes on the same value as the length by default if it is left out. For example, 0 for int and “” for string are the initial values of the elements.

Using a Composite Literal: A composite literal, which is similar to arrays but does not specify the length between the brackets, can be used to initialise slices with values.

Example: Basic Slice Declaration and Initialization

package main
import (
	"fmt"
)
func main() {
	// Slices can be created directly using a composite literal.
	dwarfs := []string{"Ceres", "Pluto", "Haumea", "Makemake", "Eris"}
	fmt.Printf("Dwarfs: %q, Type: %T\n", dwarfs, dwarfs)
	fmt.Println("Length:", len(dwarfs), "Capacity:", cap(dwarfs))
}

Output

Dwarfs: ["Ceres" "Pluto" "Haumea" "Makemake" "Eris"], Type: []string
Length: 5 Capacity: 5

Example: Creating Slices with make()

package main
import "fmt"
func main() {
	// The `make()` function is used to create a slice with a specified length and optional capacity.
	// make([]T, len, cap)
	sliceMake1 := make([]float64, 5) // len 5, cap 5 (default)
	fmt.Printf("sliceMake1 (len 5, cap 5): %v, Length: %d, Capacity: %d\n", sliceMake1, len(sliceMake1), cap(sliceMake1))
	sliceMake2 := make([]float64, 5, 10) // len 5, cap 10
	fmt.Printf("sliceMake2 (len 5, cap 10): %v, Length: %d, Capacity: %d\n", sliceMake2, len(sliceMake2), cap(sliceMake2))
	sliceMake3 := make([]int, 0, 20) // len 0, cap 20 (useful for appending later)
	fmt.Printf("sliceMake3 (len 0, cap 20): %v, Length: %d, Capacity: %d\n", sliceMake3, len(sliceMake3), cap(sliceMake3))
}

Output

sliceMake1 (len 5, cap 5): [0 0 0 0 0], Length: 5, Capacity: 5
sliceMake2 (len 5, cap 10): [0 0 0 0 0], Length: 5, Capacity: 10
sliceMake3 (len 0, cap 20): [], Length: 0, Capacity: 20

Key Functions for Slices

len() and cap():

The number of elements in the slice at any one time is returned by len( ).

The capacity of the underlying array the amount that the slice can expand without reallocation is returned by cap( ).

append(): Using this built-in function, you can dynamically append elements to a slice’s end.

  • The length is incremented and the element is inserted if the underlying array has sufficient capacity.
  • A new slice referring to the new array is returned by append, which builds a new, larger underlying array, duplicates the old elements, and adds the new ones if capacity is inadequate. Append frequently necessitates returning the result to the original slice variable because of this (slice = append(slice,…)).

Example: Appending Elements with append()

package main
import "fmt"
func main() {
	// The `append()` function adds elements to the end of a slice.
	var dynamicSlice []int // A nil slice
	fmt.Printf("Initial dynamicSlice (nil): %v, Length: %d, Capacity: %d\n", dynamicSlice, len(dynamicSlice), cap(dynamicSlice))
	dynamicSlice = append(dynamicSlice, 10)
	fmt.Printf("After append(10): %v, Length: %d, Capacity: %d\n", dynamicSlice, len(dynamicSlice), cap(dynamicSlice))
	dynamicSlice = append(dynamicSlice, 20, 30, 40)
	fmt.Printf("After append(20,30,40): %v, Length: %d, Capacity: %d\n", dynamicSlice, len(dynamicSlice), cap(dynamicSlice))
}

Output

Initial dynamicSlice (nil): [], Length: 0, Capacity: 0
After append(10): [10], Length: 1, Capacity: 1
After append(20,30,40): [10 20 30 40], Length: 4, Capacity: 4
Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index