Golang指针 [英] Golang pointers

查看:147
本文介绍了Golang指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习用Go语言进行编程。
我在理解Go指针时遇到了一些困难(而我的C / C ++现在已经很远了......)。
在环视旅游#52( http://tour.golang.org/#52)例如,我读了:

  type Vertex struct {
X,Y float64
}
$ b func(v * Vertex)Abs()float64 {
return math.Sqrt(vX * vX + vY * vY)
}

func main(){
v:=& Vertex {3,4}
fmt.Println(v.Abs())
}
pre>

但如果不是

  func(v * Vertex) Abs()float64 {
[...]
v:=& Vertex {3,4}

我写道:

  func(v顶点)Abs()float64 {
[。 ..]
v:=顶点{3,4}

甚至:

  func(v Vertex)Abs()float64 {
[...]
v:=& Vertex { 3,4}

反之亦然:

  func(v * Vertex)Abs()float64 {
[...]
v:=顶点{3,4}

我得到了完全相同的结果。是否有区别(记忆方式等)?

解决方案

您的示例中使用的Go语言有两条不同的规则:


  1. 有可能从具有值接收器的方法中推导出一个带有指针接收器的方法。因此, func(v Vertex)Abs()float64 会自动生成一个额外的方法实现:

      func(v Vertex)Abs()float64 {return math.Sqrt(vX * v.X + vY * vY)} 
    func(v * Vertex)Abs()float64 {return Vertex.Abs (* v)} //生成方法

    编译器会自动找到生成的方法:

      v:=& Vertex {3,4} 
    v.Abs()//调用生成的方法


  2. Go可以自动获取变量的地址。在以下示例中:

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

    表达式 v.Abs()与以下代码等效:

      vp:=& v 
    vp.Abs()



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://tour.golang.org/#52) for example, I read:

type Vertex struct {
    X, Y float64
}

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

func main() {
    v := &Vertex{3, 4}
    fmt.Println(v.Abs())
}

But if instead of

func (v *Vertex) Abs() float64 {
[...]
v := &Vertex{3, 4}

I wrote:

func (v Vertex) Abs() float64 {
[...]
v := Vertex{3, 4}

Or even:

func (v Vertex) Abs() float64 {
[...]
v := &Vertex{3, 4}

and vice-versa:

func (v *Vertex) Abs() float64 {
[...]
v := Vertex{3, 4}

I got the exact same result. Is there a difference (memory-wise, etc)?

解决方案

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()
    

这篇关于Golang指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆