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) { = "John"
func main() {
    var persons []Person
    p := Person{name:"David"}
    persons = append(persons, p)

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

Thanks a lot!

1 Answers

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: 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)