Go - Create Slice Example

In this example, we will show you how to create slice in Go with an example.

A slice is a dynamically-sized, flexible view into the elements of an array. A slice can grow and shrink within the bounds of the underlying array. A slice does not store any data, it just describes a section of the array.

Go - create slice simple example

A slice can be created with a slice literal.

package main

import "fmt"

func main() {
    var s1 = []int{2, 5, 6, 7, 8}

    s2 := []int{3, 5, 1, 2, 8}

    fmt.Println("s1:", s1)
    fmt.Println("s2:", s2)
}

Output:

s1: [2 5 6 7 8]
s2: [3 5 1 2 8]

Go - slice make function

We can use the make built-in function to create new slices in Go.

package main

import "fmt"

func main() {

    vals := make([]int, 5)

    fmt.Println("vals: ", vals)

    vals[0] = 1
    vals[1] = 2
    vals[2] = 3
    vals[3] = 4
    vals[4] = 5

    fmt.Println("vals: ", vals)
}

Output:

vals:  [0 0 0 0 0]
vals:  [1 2 3 4 5]

Comments