Function pointer params changes

Asked by At

I'm trying to write some function that changes a slice of structs using a pointer parameter. I did some playground with this type of code in GoPlayground and I found out that I have some mistake but I don't know what is the best way to manage it

package main

import "fmt"

type Person struct {
    name string
}

func doSomething(person *Person) {
    person.name = "John"
}
func main() {
    var persons []Person
    p := Person{name:"David"}
    persons = append(persons, p)
    doSomething(&p)
    fmt.Println(persons)    
}

doSomething isn't change anything in persons, how can I implement something like that?

Thanks a lot!

1 Answers

2
Adrian On

It changes p, but the value in persons is a copy of p, not a pointer to p (as you can see by printing p: https://play.golang.org/p/4b5fhdtuR8R). If you use a slice of pointers you'll get what you're looking for:

var persons []*Person
p := &Person{name: "David"}
persons = append(persons, p)
doSomething(p)
fmt.Println(persons[0])
fmt.Println(p)

Playground: https://play.golang.org/p/UTO1D5zKA0H