Skip to main content

How to Create a Slice in Go with a Slice Literal

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

A slice is Go's everyday list: an ordered sequence of values of one type that can grow. You write one with its type and its items in braces, []string{"red", "green", "blue"}, and grow it with append.

Syntax​

Syntax
<slice> := []<type>{<item>, <item>, <item>}
<slice> = append(<slice>, <item>)
PartWhat it does
[]<type>{...}A slice literal: creates a slice holding those items.
append(<slice>, <item>)Returns a slice with the item added at the end.
<slice>[<index>]Reads an item; the first is at 0.
len(<slice>)The number of items.

The Go specification: "Composite literals construct new values for structs, arrays, slices, and maps each time they are evaluated."

The Example​

The example starts a slice of three colors, appends a fourth, and prints the slice, its length, its first item and its last.

Prerequisites​

  • Go. go run compiles and runs a single file. This guide uses Go 1.27.4.

Step 1: Write the Code​

Create a file named main.go:

main.go, which creates colors as a string slice of red, green and blue, appends yellow, prints the slice and prints its length, colors[0] and the last item.

main.go
package main

import "fmt"

func main() {
colors := []string{"red", "green", "blue"}
colors = append(colors, "yellow")

fmt.Println(colors)
fmt.Println(len(colors), colors[0], colors[len(colors)-1])
}

colors[len(colors)-1] is the last item: the length minus one.

Step 2: Run It​

Terminal
go run main.go
Output
[red green blue yellow]
4 red yellow

A zsh terminal where go run main.go prints the slice red, green, blue, yellow and then 4 red yellow.

The command is the same in zsh, bash and PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Calling append without keeping the resultappend(c, "b") (value of type []string) is not usedAssign it back: c = append(c, "b")
Reading past the endpanic: runtime error: index out of range [4] with length 4Check len first
Expecting colors[-1] to be the last iteminvalid argument: index -1 (constant of type int) must not be negativeUse colors[len(colors)-1]

Troubleshooting​

SymptomLikely causeFix
index out of range [N] with length NAn index equal to or past the lengthIndexes run from 0 to len - 1
An append seems to do nothingIts result wasn't assignedAssign it back to the slice

FAQ​

What's the difference between a slice and an array?​

An array's length is part of its type and can't change, as in [3]string. A slice, []string, can grow, which is why most Go code uses slices.

How do I make an empty slice?​

var colors []string gives a nil slice that append works with straight away.

Conclusion​

[]type{items} creates a slice, append adds to it when you assign the result back, len counts the items and indexes run from 0 to len - 1.

Additional Resources​