How to Create a Slice in Go with a Slice Literal
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
<slice> := []<type>{<item>, <item>, <item>}
<slice> = append(<slice>, <item>)
| Part | What 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 runcompiles 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.](https://strdewiridedevblogsprod.blob.core.windows.net/images/blog/programming/go/2026/go-slice-literal-code.webp)
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
go run main.go
[red green blue yellow]
4 red yellow

The command is the same in zsh, bash and PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Calling append without keeping the result | append(c, "b") (value of type []string) is not used | Assign it back: c = append(c, "b") |
| Reading past the end | panic: runtime error: index out of range [4] with length 4 | Check len first |
Expecting colors[-1] to be the last item | invalid argument: index -1 (constant of type int) must not be negative | Use colors[len(colors)-1] |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
index out of range [N] with length N | An index equal to or past the length | Indexes run from 0 to len - 1 |
An append seems to do nothing | Its result wasn't assigned | Assign 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
- Composite literals, in the Go specification.
- Go Slices: usage and internals, on the Go blog.
