Go 语言学习(九): Structs

A struct is a collection of fields.

咱就直接上英文定义了.

然后写个程序看看:

package main

import "fmt"

type Vertex struct {
	X int
	Y int
}

func main() {
	fmt.Println(Vertex{1, 2})
}

然后运行一下:

image

OK, 然后继续编辑一下代码:

v := Vertex{1, 2}
	v.X = 4
	fmt.Println(v.X)

代码很简单, 就是告诉我们怎么访问 struct 里面的 field.

下面看看怎么结合指针使用:

	v := Vertex{1, 2}
	p := &v
	p.X = 1e9
	fmt.Println(v)

运行后结果:

image

然后我们来点儿高级的:

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

看看结果吧:

image

这就是 struct 的绝大部分的用法了. 下节我们学学 array.

posted @ 2022-09-25 18:37  YanyuWu  阅读(35)  评论(0编辑  收藏  举报