32

A Tour of Go: Basics 3

 5 years ago
source link: https://studygolang.com/articles/15304?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Struct

用指针和用变量名引用struct里的值,用法是一样的。

Struct初始化语法:

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
)

Array

数据长度是固定的,在定义时指定。

Slices

Slices的概念与Python中的概念类似,是Array的子集。

slice只是数组的引用,因此修改slice值就是修改数组里的值。

[]int{1,2,3}语法含义是先定义一个数组,再创建一个slice引用这个数组。

两个容量:

  • length:当前slice的元素个数。len(s)
  • capacity:当前slice从最左边元素开始,对应在数组里直到最后一个元素的个数。cap(s)

特殊情况:

slice的0值是nil,对应的length和capacity都是0,没有对应的数组。

a := make([]int, 0, 5) 创建一个0值数组,然后返回一个slice。

slices of slices

append function


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK