Golang pointers

后端 未结 5 706
眼角桃花
眼角桃花 2020-12-23 17:44

I am currently learning to program with Go language. I am having some difficulties understanding Go pointers (and my C/C++ is far away now...). In the Tour of Go #52 (http:/

5条回答
  •  無奈伤痛
    2020-12-23 18:15

    There are two main differences in those examples:

    func (v *Vertex) Abs()....
    

    The receiver will be passed-by-reference for v and you would be able to call this method only on pointers:

    v := Vertex{1,3}
    v.Abs() // This will result in compile time error
    &v.Abs() // But this will work
    

    On the other hand

    func (v Vertex) Abs() ....
    

    You can call this method on both pointers and structs. The receiver will be passed-by-value even when you call this method on pointers.

    v := Vertex{1,3}
    v.Abs() // This will work, v will be copied.
    &v.Abs() // This will also work, v will also be copied.
    

    You can declare both func (v *Vertex) and func (v Vertex).

提交回复
热议问题