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
}