Golang pointers

后端 未结 5 707
眼角桃花
眼角桃花 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:05

    There are two different rules of the Go language used by your examples:

    1. It is possible to derive a method with a pointer receiver from a method with a value receiver. Thus func (v Vertex) Abs() float64 will automatically generate an additional method implementation:

      func (v Vertex) Abs() float64 { return math.Sqrt(v.X*v.X+v.Y*v.Y) }
      func (v *Vertex) Abs() float64 { return Vertex.Abs(*v) }  // GENERATED METHOD
      

      The compiler will automatically find the generated method:

      v := &Vertex{3, 4}
      v.Abs()  // calls the generated method
      
    2. Go can automatically take the address of a variable. In the following example:

      func (v *Vertex) Abs() float64 { return math.Sqrt(v.X*v.X+v.Y*v.Y) }
      func main() {
          v := Vertex{3, 4}
          v.Abs()
      }
      

      the expression v.Abs() is equivalent to the following code:

      vp := &v
      vp.Abs()
      

提交回复
热议问题