声明指向结构的指针

时间:2013-12-29 05:24:48

标签: pointers go

我很困惑,因为似乎有两种方法可以在go语言中初始化指向结构的指针,而且在我看来它们在逻辑上有些相反。

var b *Vertex
var c &Vertex{3 3}

为什么一个使用*而另一个使用&如果b和c具有相同的结果类型?我很抱歉没有充分理解与此主题相关的帖子。

在这种情况下,我还没有直接讨论“接收器”的含义。我熟悉的术语是“引用(a)”或“指向(a)”或“(a)的地址”和“取消引用”或“地址的价值”。

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

有多种方法可以声明指向struct的指针并为struct字段指定值。例如,

package main

import "fmt"

type Vertex struct {
    X, Y float64
}

func main() {
    {
        var pv *Vertex
        pv = new(Vertex)
        pv.X = 4
        pv.Y = 2
        fmt.Println(pv)
    }

    {
        var pv = new(Vertex)
        pv.X = 4
        pv.Y = 2
        fmt.Println(pv)
    }

    {
        pv := new(Vertex)
        pv.X = 4
        pv.Y = 2
        fmt.Println(pv)
    }

    {
        var pv = &Vertex{4, 2}
        fmt.Println(pv)
    }

    {
        pv := &Vertex{4, 2}
        fmt.Println(pv)
    }
}

输出:

&{4 2}
&{4 2}
&{4 2}
&{4 2}
&{4 2}

参考文献:

The Go Programming Language Specification

Variable declarations

Short variable declarations

Address operators

Allocation

Composite literals

接收器用于方法。例如,v是顶点移动方法的接收器。

package main

import "fmt"

type Vertex struct {
    X, Y float64
}

func NewVertex(x, y float64) *Vertex {
    return &Vertex{X: x, Y: y}
}

func (v *Vertex) Move(x, y float64) {
    v.X = x
    v.Y = y
}

func main() {
    v := NewVertex(4, 2)
    fmt.Println(v)
    v.Move(42, 24)
    fmt.Println(v)
}

输出:

&{4 2}
&{42 24}

参考文献:

The Go Programming Language Specification

Method sets

Method declarations

Calls

Method expressions

Method values

答案 1 :(得分:1)

var c = &Vertex{3, 3}(你确实需要=)声明一个结构然后得到它的引用(它实际上分配了结构,然后得到一个指向该内存的引用(指针))。

var b *Vertex声明b是指向Vertex的指针,但根本没有初始化它。你将有一个零指针。

但是,是的,类型是相同的。

你也可以这样做:

var d *Vertex
d = &Vertex{3,3}

答案 2 :(得分:0)

除了Wes Freeman提到的内容外,您还询问了接收器。

假设你有这个:

type Vertex struct {
} 

func (v *Vertex) Hello() {
   ... do something ...
}

Vertex结构是func Hello()的接收器。所以你可以这样做:

d := &Vertex{}
d.Hello()