Menu
Coddy logo textTech

Declaring Slice Literals

Part of the Fundamentals section of Coddy's GO journey — lesson 75 of 109.

Slice literals let you create and initialize slices in a single step. They're similar to array literals but without specifying the size.

Create a slice of strings using a slice literal:

colors := []string{"red", "blue", "green"}
fmt.Println(colors)

This displays:

[red blue green]

You can also create an empty slice:

emptySlice := []int{}
fmt.Println(emptySlice, len(emptySlice))

This displays:

[] 0
challenge icon

Challenge

Beginner

In this challenge, you'll practice creating a slice literal in Go. Slice literals allow you to create and initialize a slice in a single statement.

Your task is to create a slice literal containing the names of four colors: "red", "blue", "green", and "yellow".

Cheat sheet

Slice literals let you create and initialize slices in a single step, similar to array literals but without specifying the size.

Create a slice of strings using a slice literal:

colors := []string{"red", "blue", "green"}
fmt.Println(colors) // [red blue green]

Create an empty slice:

emptySlice := []int{}
fmt.Println(emptySlice, len(emptySlice)) // [] 0

Try it yourself

package main

import "fmt"

func main() {
	// TODO: Create a slice literal named 'colors' containing the strings:
	// "red", "blue", "green", and "yellow"
	
	
	// Print the slice
	fmt.Println("Colors:", colors)
	
	// Print the length of the slice
	fmt.Println("Number of colors:", len(colors))
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals