Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Go Programming: Slice Operations

Introduction to Slices

In Go, slices are a key data type that provide a more powerful interface to sequences than arrays. Unlike arrays, slices are dynamically-sized, flexible, and have a powerful interface. Slices are much more common than arrays in idiomatic Go.

Creating Slices

Slices can be created in several ways. The most common way is using the built-in make function:

numbers := make([]int, 5)

This creates a slice of integers with a length of 5.

Another way to create a slice is by slicing an existing array:

arr := [5]int{1, 2, 3, 4, 5}

slice := arr[1:4]

This creates a slice that includes elements from index 1 to 3 of the array arr.

Accessing Elements

Elements in a slice can be accessed using the index operator []. Indexing starts at 0.

fmt.Println(slice[0])

This prints the first element of the slice.

Modifying Slices

Slices are mutable, meaning that you can change their elements. Here's an example:

slice[0] = 10

This changes the first element of the slice to 10.

Appending to Slices

You can add elements to a slice using the built-in append function. This function returns a new slice with the additional elements.

numbers := []int{1, 2, 3}

numbers = append(numbers, 4, 5)

fmt.Println(numbers) will output [1 2 3 4 5]

Length and Capacity

Slices have both a length and a capacity. The length of a slice is the number of elements it contains. The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.

numbers := []int{1, 2, 3}

fmt.Println(len(numbers)) // Output: 3

fmt.Println(cap(numbers)) // Output: 3

Copying Slices

You can copy elements from one slice to another using the built-in copy function.

src := []int{1, 2, 3}

dest := make([]int, 3)

copy(dest, src)

Now dest contains [1 2 3].

Slicing Slices

You can create a new slice by slicing an existing slice. This creates a new view of the same underlying array.

numbers := []int{1, 2, 3, 4, 5}

slice := numbers[1:4]

This creates a slice that includes elements from index 1 to 3 of the numbers slice, resulting in [2 3 4].

Conclusion

Slices are a powerful and flexible way to work with sequences in Go. Understanding how to create, modify, and manipulate slices is essential for effective Go programming. With slices, you can handle data efficiently and with ease.