3

#yyds干货盘点#【愚公系列】2022年08月 Go教学课程 020-Go容器之数组

 2 years ago
source link: https://blog.51cto.com/u_15437432/5611498
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容器之数组

1.什么是数组

数组(Array)是有序的元素序列。 若将有限个类型相同的变量的集合命名,那么这个名称为数组名。组成数组的各个变量称为数组的分量,也称为数组的元素,有时也称为下标变量。用于区分数组的各个元素的数字编号称为下标。数组是在程序设计中,为了处理方便, 把具有相同类型的若干元素按有序的形式组织起来的一种形式。 这些有序排列的同类数据元素的集合称为数组。–百度百科

数组是一段固定长度的连续内存区域。

2.Go语言中数组

在 Go 语言数组一旦声明,数组的大小就确定了,不能修改大小但可以修改数组成员。

Go 语言定义数组的格式如下:

var 数组变量名 [元素数量]T
  • 数组变量名: 定义一个数组的变量名
  • 元素数量:定义数组的大小
  • T 可以是任意基本类型,甚至可以是数组本身,若为数组,则可以实现多维数组

相关案例:

package main

import (
	"fmt"
)

func main()  {
	// 定义一个变量为 arr, 成员类型为 string, 大小为 3 的数组
	var arr [3]string

	// 赋值操作
	arr[0] = "愚公1号"
	arr[1] = "愚公2号"
	arr[2] = "愚公3号"

	fmt.Println(arr)
}
#yyds干货盘点#【愚公系列】2022年08月 Go教学课程 020-Go容器之数组_数组

3.初始化数组

package main

import (
	"fmt"
)

func main() {
	// 定义一个变量为 arr, 成员类型为 string, 大小为 3 的数组
	var arr = [3]string{"愚公1号", "q愚公2号", "愚公3号"}
	fmt.Println(arr)
}

#yyds干货盘点#【愚公系列】2022年08月 Go教学课程 020-Go容器之数组_变量名_02

4.数组的遍历

package main

import (
"fmt"
)

func main()  {
	// 定义一个变量为 arr, 成员类型为 string, 大小为 3 的数组
	var arr = [...]string{"愚公1号", "q愚公2号", "愚公3号"}

	for index, v := range arr {
		fmt.Printf("index: %d, value: %s\n", index, v)
	}
}
#yyds干货盘点#【愚公系列】2022年08月 Go教学课程 020-Go容器之数组_数组_03

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK