Menu
Coddy logo textTech

Creating Slices with `make`

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

The make function creates slices with a specified length and capacity.

Create a slice of integers with length 3:

numbers := make([]int, 3)
fmt.Println(numbers)

This displays:

[0 0 0]

Create a slice with length 2 and capacity 5:

scores := make([]int, 2, 5)
fmt.Println(scores, len(scores), cap(scores))

This displays:

[0 0] 2 5
challenge icon

Challenge

Beginner

In this challenge, you'll practice creating a slice using the make function. The make function allows you to create a slice with a specific length and capacity.

Your task is to create a slice of strings with a length of 3 and a capacity of 5 using make, then assign some values to it and print the slice.

After printing the slice, you should also print its length and capacity.

Cheat sheet

The make function creates slices with a specified length and capacity.

Create a slice with specified length:

numbers := make([]int, 3)
// Creates [0 0 0]

Create a slice with length and capacity:

scores := make([]int, 2, 5)
// Creates slice with length 2, capacity 5

Use len() and cap() to check slice properties:

fmt.Println(scores, len(scores), cap(scores))
// Output: [0 0] 2 5

Try it yourself

package main

import "fmt"

func main() {
	// TODO: Create a slice of strings with length 3 and capacity 5 using make
	// var names = ...
	
	// Assign values to the slice
	names[0] = "Alice"
	names[1] = "Bob"
	names[2] = "Charlie"
	
	// Print the slice
	fmt.Println("Names:", names)
	
	// Print the length and capacity of the slice
	fmt.Printf("Length: %d, Capacity: %d\n", len(names), cap(names))
}
quiz iconTest yourself

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

All lessons in Fundamentals