Working with Slices

Go has an array type, but it has a fixed size. Slices in Go are dynamically-sized and more flexible. Slices are the common data type you will work with.

The specification for slices are []T where T is the type, for example []string is a set of strings, or []int is a set of integers.


Initialize an empty slice

var empty []int

Initialize a slice with values

alphas := []string{"abc", "def", "ghi", "jkl"}


Slices can not be modified, a new copy needs to be made

var nums []int
nums = append(nums, 203)
nums = append(nums, 302)
// [203 302]

You can append multiple values at once

alphas := []string{"abc", "def", "ghi", "jkl"}
alphas = append(alphas, "mno", "pqr", "stu")

Common Array Operations

Get length of a slice

fmt.Println("Length: ", len(alphas))

Retrieve a single element from slice


Retrieve a slice of a slice

alpha2 := alphas[1:3]


There is no built-in function to determine if an element exists in a slice. Here is an example function to check if a string exists in an array of strings.

package main

import "fmt"

func main() {

	alphas := []string{"abc", "def", "ghi", "jkl"}

	if elemExists("def", alphas) {

func elemExists(s string, a []string) bool {
	for _, v := range a {
		if v == s {
			return true
	return false