Alex Netkachov
Alex Netkachov

Reputation: 13522

How to return slice by reference?

The returned slice by reference is empty:

package main

import "fmt"

func GetItems(items *[]string) {
    list := make([]string, 0)
    list = append(list, "ok")
    items = &list
}

func main() {
    var items []string
    GetItems(&items)
    fmt.Print(len(items)) // expect 1 here, but got 0
}

How to return the slice from the function by reference?

Upvotes: 1

Views: 238

Answers (1)

fuz
fuz

Reputation: 92966

By assigning to items, you alter where items points, not the value items points to. To do the latter, instead of items = &list write *items = list.

Upvotes: 5

Related Questions