6

Go 语言入门系列:数组的使用

 3 years ago
source link: https://studygolang.com/articles/35186
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.
neoserver,ios ssh client

Go 语言入门系列:数组的使用

liumiao1128 · 大约8小时之前 · 65 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    

Go 中常用的容器

Golang 中以标准库的方式提供了常用的容器实现,基本能够满足我们日常开发的需要。我们来具体学习下 Go 数组的使用。

Go 语言提供了数组类型的数据结构。

数组是具有相同唯一类型的一组已编号且长度固定的数据项序列,这种类型可以是任意的原始类型例如整型、字符串或者自定义类型。

相对于声明 number0, number1, ..., number99 的变量,使用数组形式 numbers[0], numbers[1] ..., numbers[99] 更加方便且易于扩展。

数组元素可以通过索引(位置)来读取(或者修改),索引从 0 开始,第一个元素索引为 0,第二个索引为 1,以此类推。数组的声明样式如下所示:

var name [size]T 数组大小必须指定,可以是一个常量或者表达式,但必须在静态编译时就确定其大小,不能动态指定。T 表示数组成员的类型,可为任意类型。

对数组的初始化和使用与其他语言一般无二,可以在声明时使用初始化列表对数组进行初始化,也可以通过下标对数据成员进行访问和赋值,如下所示:

func main()  {
 var classMates1 [3]string
 classMates1[0] = "小明"
 classMates1[1] = "小红"
 classMates1[2] = "小李" // 通过下标为数组成员赋值
 fmt.Println(classMates1)
 fmt.Println("The No.1 student is " + classMates1[0]) // 通过下标访问数组成员

 classMates2  := [...]string{"小明", "小红", "小李"} // 使用初始化列表初始化列表
 fmt.Println(classMates2)

}

在使用初始化列表初始化数组时,需要注意 [] 内的数组大小需要和 {} 内的数组成员的数量一致,上述例子中我们使用 ... 让编译器为我们根据 {} 内成员的数量确定数组的大小。

除此之外,我们还可以使用指针操作数组,如下例子所示:

classMates3 := new([3]string)
classMates3[0] = "明"
classMates3[1] = "红"
classMates3[2] = "王"
fmt.Println(*classMates3)

我们通过 new 函数申请了 [3]string 的内存空间,并返回了其对应的指针。需要注意的是,该指针无法支持偏移和运算,这是 Golang 对指针类型的限制。我们可以通过指针直接操作数组,与 C 语言中的指针功能无异。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK