In the Go programming language; how can pointers to pointers become useful?
(Why are they not illegal if they are not really useful?)
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