What are pointers to pointers good for?

后端 未结 5 1613
难免孤独
难免孤独 2021-02-04 10:01

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

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

5条回答
  •  盖世英雄少女心
    2021-02-04 10:57

    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
    

提交回复
热议问题