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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?