數組初始化
package main
import (
"fmt"
)
func main() {
//定長,沒有初始值
a := [2]int{}
//定長定義初始值
b := [2]int{1, 2}
//不定長具有初始值
c := [...]int{1, 2}
//new得到數組引用
d := new([2]int)
fmt.Println(a, b, c, d)
}
運行結果
chenlilong@DESKTOP-B9ALUUJ MINGW64 /d/gopath/src
$ go run main.go
[0 0] [1 2] [1 2] &[0 0]
數組的注意事項
1、定長數組初始化,不一定初始化所有值,未被初始化的值,使用默認值代替(如int使用0)
2、可以使用下標的方式進行初始化
3、不定長數組是要用... ,注意區別數組與slice的不定長區別(數組和slice的內存結構不一樣)
4、new初始化數組的是引用,但是仍然可以用下標進行賦值
5、new初始化的數組必須指定長度,也不定進行賦值
6、數組的可以進行==比較,比較類型與長度,不是比較地址
7、數組的傳遞是值傳遞
8、可以使用range遍歷(注意值傳遞)
9、長度和類型是數組的一部分,不同長度和不同類型不能進行比較,例如[2]int{} 不能和 [3]int{3}
10、數組初始化以後就是定長的,例如 [...]int{0,0} 可以和 [2]int{0,0} 比較
11、可以使用len 和 cap
package main
import (
"fmt"
)
func main() {
//默認值
a := [3]int{1}
//使用下標方式初始化
b := [3]int{1: 1}
//區別slice
c1 := [...]int{1, 2, 3} //這是不定長數組
c2 := []int{1, 2, 3} //這是slice
//new
d := new([2]int)
d[0] = 1
// d := new([2]int{1,2})
// d := new([...]int{0,0})
fmt.Println(a, b, c1, c2, d)
//數組的比較
e1 := [2]int{}
e2 := [...]int{0, 0}
fmt.Println(e1 == e2)
//數組的值傳遞
f1 := [2]int{}
var f2 = f1
fmt.Println(f1 == f2)
f1[0] = 1
fmt.Println(f1, f2)
fmt.Println(f1 == f2)
//可以使用len,cap
fmt.Println(len(a), cap(a))
//比較
g1 := [...]int{0, 0}
g2 := [2]int{0, 0}
fmt.Println(g1 == g2)
}
運行結果
chenlilong@DESKTOP-B9ALUUJ MINGW64 /d/gopath/src
$ go run main.go
[1 0 0] [0 1 0] [1 2 3] [1 2 3] &[1 0]
true
true
[1 0] [0 0]
false
3 3
true