Alex Rivera | Logout

What are pointers to pointers good for?

Asked 2012-01-07T08:23:01.783
19

In the Go programming language; how can pointers to pointers become useful?

(Why are they not illegal if they are not really useful?)

Edit
Report

1 Answer

28

When you pass a pointer to function, function gets a copy of it. So assigning new value to the given pointer will not result in assigning it to the original one:

type Smartphone struct {
    name string
}

type Geek struct {
    smartphone *Smartphone
}

func replaceByNG(s **Smartphone) {
    *s = &Smartphone{"Galaxy Nexus"}
}

func replaceByIPhone(s *Smartphone) {
    s = &Smartphone{"IPhone 4S"}
}

func main() {
    geek := Geek{&Smartphone{"Nexus S"}}
    println(geek.smartphone.name)

    replaceByIPhone(geek.smartphone)
    println(geek.smartphone.name)

    replaceByNG(&geek.smartphone)
    println(geek.smartphone.name)
}

The output is:

Nexus S
Nexus S
Galaxy Nexus
answered 2012-01-07T10:51:12.137

Your Answer