在本教程中,我们将介绍 Go 数组数据类型,它属于复合类型中的聚合数据类型。正如我们在上一教程中讨论过的,Go 包含一些原始的基本数据类型:int、float、complex numbers、Boolean 和 string。在此,我们将介绍什么是聚合数据类型及其分类,以及其数组和结构体等分类的声明和语法。
Golang 中的数组是具有相同类型元素的固定长度的数据结构。在数组数据类型中,您必须在初始化或声明它们时定义大小。它们可以包含零个或多个元素。

缺点:一旦创建,数组的大小就无法调整。因此,数组在 Go 程序中不常用,但它们构成了切片和映射的基础。
优点:在结构体类型中,您可以存储多种基本数据类型的多个值,例如 int、float、string,并将它们视为一个整体。
要在 Golang 中将变量声明为数组类型,请遵循以下语法
var <variable name> <size of array><data type>
示例
var a[4]int
变量“a”使用 var 关键字声明,它可以容纳大小为 4 的整数类型值,即变量“a”可以容纳 4 个数值元素。变量可以是任何数据类型,如 string、float 等。


<variable name> := <size of array>.<data type{<value1><value2>.....}
示例
colors := [3]string{"blue", "orange", "yellow"}
声明了一个名为“colors”的字符串类型变量,它包含三个元素,如蓝色、橙色、黄色。

在数组中,元素通过指示每个数组元素对应的索引号来赋值或访问。方括号 [ ] 指定相应的数组索引。例如 A [1],A [5]。
让我们通过简单的 Go 程序来理解上述定义的语法
package main
import "fmt"
func main() {
var a [4]int //Declare array
a[1] = 1 //initialize array values
a[3]= 3
fmt.Println(a[0]) //print statement displays variable values
fmt.Println(a[1])
fmt.Println(a[2])
fmt.Println(a[3])
}
输出
0 1 0 3
说明
import "fmt"
func main() {
//Declare a array
//colors[0] =”blue”
//colors[1] =”orange”
//colors[2] =”yellow
colors := [3]string{"blue", "orange", "yellow"} //shorthand array declaration
print(colors)
}
func print(colors [3]string) { //Pass array as a function argument
fmt.Println(colors)}
输出
[blue orange yellow]
省略号是声明和初始化数组的另一种方式,当已知数据量但位置未知时。省略号用 (...) 表示,如下面的示例所示
s := [...]int{4, 5, 6}
让我们修改上一节使用的程序以使用省略号。代码应如下所示
package main
import "fmt"
func main() {
//Declare a array
//colors[0] =”blue”
//colors[1] =”orange”
//colors[2] =”yellow
colors := [...]string{"blue", "orange", "yellow"} //ellipsis array declaration
print(colors)
}
输出
[blue orange yellow]
数组允许在声明数组时为其包含的元素初始化特定值。
使用简短声明声明了一个数组 A,数组大小为 6。为某些数组元素指定了三个值。将值 50 分配给第二个元素(索引 1),将值 30 分配给第四个元素(索引 3),将值 30 分配给第六个元素(索引 5)
示例
package main
import "fmt"
func main() {
//initializing values to specific array elements
A := [6]int{1: 50, 3: 30,5:50}
fmt.Println("Initializing values to specific array elements \n",A)
fmt.Println("Default type of unspecified elements is 0 \n")
}
输出
Initializing values to specific array elements [0 50 0 30 0 50] Default type of unspecified elements is 0
注意: 如果未指定值,整数类型的默认值为零,字符串类型的默认值为空格“” 。
Golang 支持一维 (1-D) 数组以及多维数组。
Golang 中的多维数组支持处理复杂的数据结构。
您可以使用以下语法创建多维数组
语法
var <variable_name>[size 1][size 2]….[size m]<type>
示例
var twoDM [3][5]int //Two dimensional array
var threeDM [4][2][3]int //Three dimensional array
关键字 var 后面跟着一个变量名,如 twoDM(2D) 表示它是 3*5 的矩阵类型,有 3 行 5 列。类似地,也声明了三维数组。

package main
import "fmt"
func main() {
var twoD [3][2]int
for i := 0; i < 3; i++ {
for j := 0; j < 2; j++ {
twoD[i][j] = (i + 1) * (j + 1)
}
fmt.Println("Row", i, twoD[i])
}
fmt.Println("\nExample of multi dimensional :", twoD)
}
输出
Row 0 [1 2] Row 1 [2 4] Row 2 [3 6] Example of multi dimensional : [[1 2][2 4][3 6]]
有两种类型
a = [3][2]int{
{1,2} , /* initialize a[0] row indexed by 0 */
{2,4} , /* initializer a[1] row indexed by 1 */
{3,6} /* initializer a[2] row indexed by 2 */
}
var a = [3][2]int{ {0,0}, {8,2}, {2,4}, {3,9},{4,7}}
在 Golang 中,可以使用 len() 函数来识别数组的长度。len() 函数返回一个整数类型,表示数组中定义的元素总数。
len (variable name)

colors := [4]string{"blue ","black","white","orange"} length := len(colors)
上面提供的代码显示了 colors 的声明,它是一个大小为 4 的数组,包含 4 种不同的颜色。函数 len(变量名) 返回值 4,这里变量名是 color,所以调用函数 len(colors)
示例
package main
import "fmt"
func main() {
// Create an exmaple array
array := []int{1, 2, 3, 4, 5}
//create array with var keyword of string type & assign values
var array1 [3]string
array1[0] ="Go"
array1[1] ="Lang"
// Print number of items
fmt.Println("First array ",array)
fmt.Println("Array Length:", len(array))
fmt.Println("Second array ",array1)
fmt.Println("Length of array1 :", len(array1))
// Add an item and print again
array = append(array, 6)
fmt.Println(" Length after apppending element to array :", len(array))
}
输出
First array [1 2 3 4 5] Array Length : 5 Second array [Go Lang] Length of array1 : 3 Length after appending element to an array : 6
要确定数组中是否存在特定元素,请使用 for 循环进行迭代,然后使用 if 条件检查数组中的元素。
语法:
key word itemExists<variable name><item needs to check>

关键字 itemExists 后面跟着变量名以及需要在数组中检查的元素是否存在,根据其评估结果返回 true 或 false。如果元素存在则返回 True,否则返回 False。
示例
package main
import (
"fmt"
"reflect"
)
func main() {
//Declare array of type string
Array := [4]string{"Green", "blue", "orange", "yellow"}
fmt.Println(itemExists(Array, "Green")) //item exist returns true
fmt.Println(itemExists(Array, "orange")) //item exist returns true
fmt.Println(itemExists(Array, "white")) //item does not exist returns false
}
func itemExists(arrayType interface{}, item interface{}) bool {
arr := reflect.ValueOf(arrayType)
if arr.Kind() != reflect.Array {
panic("Invalid data-type")
}
for i := 0; i < arr.Len(); i++ {
if arr.Index(i).Interface() == item {
return true
}
}
return false
}
输出
true true false
Golang 支持数组过滤,即从数组包含的元素集中选择所需的元素
语法
Array elements are filtered using the symbol “: “
示例
package main
import "fmt"
func main() {
colors := [...]string{"green", "orange", "white", "blue", "red"}
fmt.Printf("colors: %v\n", colors)
fmt.Printf(":2 %v\n", colors[:2]) //Return first 2 elements
fmt.Printf("1:3 %v\n",colors[1:3]) // return first 2 elements exclude 3rd element
fmt.Printf("2: %v\n", colors[2:])
}
输出
colors : [green orange white blue red] : 2 [green orange] 1: 3 [orange white] 2 : [white blue red]
可以通过创建新的数组类型变量并为新数组赋值或传递其引用类型来将数组复制到另一个数组。
示例
package main
import "fmt"
func main() {
Array1:= [3]string{"orange", "yellow", "white"}
Array2:= Array1 // elements are passed by value
Array3:= &Array1; // elements are passed by reference
fmt.Printf ("Display Array1: %v\n", Array1) //Display array1
fmt.Printf ("Display Array2: %v\n", Array2) //Display copied elements in Array2
Array1[0] = "green"
fmt.Printf("Display Array1 after appending new value: %v\n", Array1)
fmt.Printf("*Array3: %v\n", *Array3) //Display array 1 element passed by reference
}
输出
Display Array1: [orange yellow white] Display Array2: [orange yellow white] Display Array1 after appending new value : [green yellow white] *Array3 : [green yellow white]