What's the point of having pointers in Go?

前端 未结 4 432
长情又很酷
长情又很酷 2020-12-12 15:45

I know that pointers in Go allow mutation of a function\'s arguments, but wouldn\'t it have been simpler if they adopted just references (with appropriate const or mutable q

4条回答
  •  臣服心动
    2020-12-12 16:38

    I really like example taken from http://www.golang-book.com/8

    func zero(x int) {
        x = 0
    }
    func main() {
        x := 5
        zero(x)
        fmt.Println(x) // x is still 5
    }
    

    as contrasted with

    func zero(xPtr *int) {
        *xPtr = 0
    }
    func main() {
        x := 5
        zero(&x)
        fmt.Println(x) // x is 0
    }
    

提交回复
热议问题