0
0
Goprogramming~5 mins

Slice creation in Go

Choose your learning style9 modes available
Introduction

Slices let you work with lists of items that can grow or shrink. They are easy to use and flexible.

When you want to store a list of names that can change size.
When you need to collect user inputs one by one.
When you want to pass a group of numbers to a function.
When you want to create a dynamic list instead of a fixed array.
When you want to easily add or remove items from a list.
Syntax
Go
var s []Type
s := []Type{value1, value2, value3}
s := make([]Type, length, capacity)

Type is the kind of data you want to store, like int or string.

make creates a slice with a set length and optional capacity.

Examples
This creates an empty slice of integers. It has no items yet.
Go
var numbers []int
This creates a slice with three fruit names already inside.
Go
fruits := []string{"apple", "banana", "cherry"}
This creates a slice of strings with length 3, all empty strings initially.
Go
letters := make([]string, 3)
This creates a slice of integers with length 2 and capacity 5, meaning it can grow up to 5 items without needing new memory.
Go
data := make([]int, 2, 5)
Sample Program

This program shows different ways to create slices and how to add items to an empty slice.

Go
package main

import "fmt"

func main() {
    // Create an empty slice of strings
    var colors []string
    fmt.Println("Empty slice:", colors)

    // Create a slice with initial values
    fruits := []string{"apple", "banana", "cherry"}
    fmt.Println("Fruits slice:", fruits)

    // Create a slice with make
    numbers := make([]int, 3)
    fmt.Println("Numbers slice with length 3:", numbers)

    // Add items to the empty slice
    colors = append(colors, "red", "green")
    fmt.Println("Colors after append:", colors)
}
OutputSuccess
Important Notes

Slices are like windows to arrays; they point to underlying data.

Appending to a slice may create a new underlying array if capacity is exceeded.

Zero value of a slice is nil, which behaves like an empty slice.

Summary

Slices hold lists of items that can change size.

You can create slices empty, with values, or with make.

Use append to add items to slices.