duanna3634
2016-08-11 01:03
浏览 3
已采纳

前往教学课程:这行的作用是什么?

I am doing the go tutorial and I had a question about this exercise... https://tour.golang.org/moretypes/5

I have only briefly worked with pointers and addresses in rudimentary C code before. My understanding is that the line p = &Vertex{1, 2} // has type *Vertex is pointing a new variable p to the address of Vertex.

Wouldn't this then be redefining the definition of the struct to set X, Y int = 1, 2

Here is the full code from the tutorial:

package main

import "fmt"

type Vertex struct {
    X, Y int
}

var (
    v1 = Vertex{1, 2}  // has type Vertex
    v2 = Vertex{X: 1}  // Y:0 is implicit
    v3 = Vertex{}      // X:0 and Y:0
    p  = &Vertex{1, 2} // has type *Vertex
)

func main() {
    fmt.Println(v1, p, v2, v3)
}
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongyan7988 2016-08-11 02:32
    已采纳

    var p = &Vertex{1, 2} does the following:

    • Creates an anonymous variable of type Vertex with the values 1 for x and 2 for y
    • Creates a variable p of type *Vertex (pointer to Vertex)
    • Sets p to point to the anonymous variable.

    It doesn't affect the definition of the type.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题