数据结构——容器
一、数组
- 数组声明:
1 | var 变量名 [元素个数]Type |
- 初始化数组
- 声明时初始化元素个数进行元素设置(需要保证元素个数和数组大小一致)
1 | var nums = [6]int{1,2,3,4,5,6} |
- 编译器元素个数 (…代替元素个数,编译器自动确定数组大小)
1
var books = [...]string{"apple","xiaomi","dell"}
- 遍历数组
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18package main
import "fmt"
func main() {
var book [3]string
book[0] = "apple"
book[1] = "xiaomi"
book[2] = "dell"
for k, v := range book {
fmt.Printf("book%d v==>%s\n", k, v)
}
}
// 输出
$ go run "./遍历数组.go"
book0 v==>apple
book1 v==>xiaomi
book2 v==>dell
二、切片
数组是声明时分配一段固定长度的内存区域,而切片是动态分配大小的连续空间,切片内部结构包含地址,大小,容量。
- 从数组或者切片生成新的切片
- 本文作者: ChuLinx
- 本文链接: http://yoursite.com/2019/12/19/Go语言复习笔记——容器之数组和切片/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!