小编mer*_*ard的帖子

Golang指针

我目前正在学习用Go语言编程.我在理解Go指针方面遇到了一些困难(现在我的C/C++还很远......).例如,在Tour of Go#52(http://tour.golang.org/#52)中,我读到:

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())
}
Run Code Online (Sandbox Code Playgroud)

但如果不是

func (v *Vertex) Abs() float64 {
[...]
v := &Vertex{3, 4}
Run Code Online (Sandbox Code Playgroud)

我写:

func (v Vertex) Abs() float64 {
[...]
v := Vertex{3, 4}
Run Code Online (Sandbox Code Playgroud)

甚至:

func (v Vertex) Abs() float64 {
[...]
v := &Vertex{3, 4}
Run Code Online (Sandbox Code Playgroud)

反之亦然:

func (v *Vertex) Abs() float64 {
[...]
v := Vertex{3, …
Run Code Online (Sandbox Code Playgroud)

pointers go

21
推荐指数
2
解决办法
1万
查看次数

标签 统计

go ×1

pointers ×1