-1

In the below code, why are both fmt.Println(len(people)) printing 0? As pointed out here, https://stackoverflow.com/a/2441112/315445, and elsewhere, slice is reference type. Why isn't caller (main) seeing the updated data?

package main

import "fmt"

type Person struct {
    name string
    age string
}

func main() {
    var people = make([]Person, 0)
    fmt.Println(len(people))
    getList(people)
    fmt.Println(len(people))
}

func getList(people []Person) {
    people = append(people, Person {"Foo", "1"})
    people = append(people, Person {"Bar", "2"})
}

But this works. So its not actually a pass-by-reference?

package main

import "fmt"

type Person struct {
    name string
    age string
}

func main() {
    var people = make([]Person, 0)
    fmt.Println(len(people))
    people = getList(people)
    fmt.Println(len(people))
}

func getList(people []Person) []Person {
    people = append(people, Person {"Foo", "1"})
    people = append(people, Person {"Bar", "2"})
    return people
}
Community
  • 1
  • 1
Null Head
  • 2,877
  • 13
  • 61
  • 83

1 Answers1

1

A slice contains a pointer to the backing array, length and capacity. The append built-in returns a new slice with a new length and possibly a new pointer to a reallocated backing array.

Slices are passed by value. Changes to the slice in getList are not visible in the caller. Changes to the backing array are visible to the caller.

A slice is called a reference type because a slice contains a pointer to the backing array.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242