go array 特性
1、数组是值类型,赋值和传参会复制整个数组,⽽不是指针。
func printArray(x [2]int) {
fmt.Printf("the array x address is:%p\n", &x)
x[1] = 1000
}
func test1() {
var a [2]int = [2]int {1}
fmt.Printf("the array a address is:%p\n", &a)
fmt.Printf("the value of a:%v\n", a)
printArray(a)
}
输出:
the array a address is:0xc0000a2070
the value of a:[1 0]
the array x address is:0xc0000a20a0
值拷⻉⾏为会造成性能问题,通常会建议使⽤ slice,或数组指针。
2、数组⻓度必须是常量,且是类型的组成部分。[2]int 和 [3]int 是不同类型。
如果类型相同,数组⽀持 “==”、"!=" 操作符,用来判断数组的值是否相同。
func test2() {
a := [2]int {1,2}
b := [2]int {1,2}
// error:non-constant array bound length
// var length int = 3
// c := [length]int {}
c := [3]int {}
fmt.Printf("the type of a: %T, the value: %v\n", a, a)
fmt.Printf("the type of b: %T, the value: %v\n", b, b)
fmt.Printf("the type of c: %T, the value: %v\n", c, c)
if a == b {
fmt.Printf("a == b\n")
fmt.Printf("the address of a: %p\n", &a)
fmt.Printf("the address of b: %p\n", &b)
}
// error: invalid operation: a != c (mismatched types [2]int and [3]int)
// if a != c {
// fmt.Printf("a != c\n")
// fmt.Printf("the address of a: %p\n", &a)
// fmt.Printf("the address of c: %p\n", &c)
// }
}
输出:
he type of a: [2]int, the value: [1 2]
the type of b: [2]int, the value: [1 2]
the type of c: [3]int, the value: [0 0 0]
a == b
the address of a: 0xc000012090
the address of b: 0xc0000120a0
3、指针数组 [n]*T,数组指针 *[n]T。
4、数组的初始化
func test3() {
a := [3]int {1,2} // 未初始化元素值为 0。
b := [...]int {1,2,3,4} // 通过初始化值确定数组⻓度。
c := [5]int {2:10, 4:100} // 使⽤索引号初始化元素。
d := [...]int {3:100, 5:100} // 可以利用索引确定数组长度
e := [...]struct {
name string
age int
} {
{"chen",25}, // 可省略元素类型。
{"yang",25}, // 别忘了最后⼀⾏的逗号。
}
fmt.Printf("the type of a: %T, the value: %v\n", a, a)
fmt.Printf("the type of b: %T, the value: %v\n", b, b)
fmt.Printf("the type of c: %T, the value: %v\n", c, c)
fmt.Printf("the type of d: %T, the value: %v\n", d, d)
fmt.Printf("the type of e: %T, the value: %v\n", e, e)
}
输出:
the type of a: [3]int, the value: [1 2 0]
the type of b: [4]int, the value: [1 2 3 4]
the type of c: [5]int, the value: [0 0 10 0 100]
the type of d: [6]int, the value: [0 0 0 100 0 100]
the type of e: [2]struct { name string; age int }, the value: [{chen 25} {yang 25}]
5、多维数组,先确定列的数量,再确定行的数量。
func test4() {
a := [2][3]int {{1,1,1}, {2,2,2}}
b := [...][2]int { // 第 2 纬度不能⽤ "..."。
{1,1},
{2,2},
{3,3},
}
fmt.Printf("the type of a: %T, the value: %v\n", a, a)
fmt.Printf("the type of b: %T, the value: %v\n", b, b)
}
输出:
the type of a: [2][3]int, the value: [[1 1 1] [2 2 2]]
the type of b: [3][2]int, the value: [[1 1] [2 2] [3 3]]
6、数组长度。
func test5() {
a := [2]int {}
fmt.Println("the len of a: ", len(a)," the cap of a: ", cap(a))
}
输出:
the len of a: 2 the cap of a: 2
内置函数 len 和 cap 都能返回数组⻓度 (元素数量)。