Working With Slices In Go

Working With Slices In Go

Learn How To Work With Slices in GoLang

In this tutorial, we'll learn how to use the Go built-in functions len, append, and cap.

Len

We use the len function to find the length of an array, slice, or a string.

This code example shows how to get the length of a string and the length of a slice:

package main

import "fmt"

func main() {

	// Get the length of a string.
	strLen := len("This is a string")
	fmt.Printf("str_len: %d\n", strLen)

	// Get the length of a slice.
	numbers := []int{50, 40, 30, 20, 10}
	numLen := len(numbers)
	fmt.Printf("The slice numbers as a length of: %d\n", numLen)
}

Append

We use the append function to add new elements to a slice.

This code example shows how to add elements to a slice of integers:

package main

import "fmt"

func main() {

	// Create a slice of integers.
	numbers := []int{0, 10, 20}

	// Add a integer to the slice.
	numbers = append(numbers, 30)

	// Print index and the integers the in slice.
	for i, n := range numbers {
		fmt.Printf("Index: %d | Value: %d\n", i, n)
	}
}

Cap

We use the cap function to get the capacity of a slice.

This code example shows how to get the capacity of a slice:

package main

import "fmt"

func main() {

	// Create a slice of integers.
	numbers := []int{10, 20, 30}

	// Get the capacity of the slice.
	numbersCap := cap(numbers)
	fmt.Printf("The numbers slice as a capacity of: %d\n", numbersCap) // Currently this will be 3.

	// Add new integer to the slice.
	numbers = append(numbers, 40)

	// The capacity will double here.
	numbersCap = cap(numbers)
	fmt.Printf("The numbers slice now as a capacity of: %d\n", numbersCap) // Currently this will be 6.

}

Source Code

You can find all the source code at Go-Examples on GitLab.

Did you like it? Why don't you try also...

How to remove the first character of a string in Golang

How to remove the first character of a string in Golang

Learn how to remove first the character of a string in GoLang

Go Strings Cheat Sheet Part 1

Go Strings Cheat Sheet Part 1

Learn the Basic of Working with GoLang Strings.

How to Convert GoLang Integer to String Conversion

How to Convert GoLang Integer to String Conversion

Learn how to convert integers to strings and how to convert strings to integers in GoLang