数组类型
1、定义
var 变量名 [len]type
2、举例
var a [5]int
var a [5]string
var a [5]float32
var a [15]bool
3、使用下标访问,比如:a[0]访问第一个元素
4、数组的内存布局是连续的内存布局
package main import( "fmt" ) func main() { var a [25]int8 length := len(a) for i := 0; i < length; i++ { fmt.Printf("%p\n", &a[i])//打印内存地址 } }
5、数组的长度
var a [10]int
length :=len(a)
6、数组遍历
下标遍历
for……range
package main import( "fmt" ) func main() { var a [25]int8 for index, value := range a { fmt.Printf("a[%d]=%d\n", index, value) } }
7、数组也是指类型
package main import( "fmt" ) func test2() { var a [5] int = [5]int {1,2,3,4,5} var b [5] int b = a fmt.Printf("b=%v\n", b) b[0] = 200 fmt.Printf("b=%v\n", b) fmt.Printf("a=%v\n", a) }
8、初始化
var a [5] int = [5]int{1,2,3,4,5}
var a = [5]int{1,2,3,4,5}
var a = [5]int{1,2,3}
var a = [...]int{1,2,3,4,5}
var a = [5]string{1:‘abc‘,4:‘efg‘}
package main import( "fmt" ) func main() { var a [5] int = [5]int{1,2,3,4,5} fmt.Printf("%v\n", a) var b = [...]int{1,3,4,5,7, 8} fmt.Printf("%v\n", b) var c = [5]int{1,3,4} fmt.Printf("%v\n", c) var d [5]string = [5]string{1:"abc", 4:"efg"} fmt.Printf("%#v\n", d) }