go的array
点击查看代码
package main
import (
"fmt"
)
func testArray1() {
var a [5]int
fmt.Println(a)
a[0] = 200
a[1] = 300
fmt.Println(a)
}
func testArray3() {
//var a [5]int = [5]int{1, 2, 3, 4, 5}
//a := [5]int{1, 2, 3, 4, 5} // 也可以这样写
a := [...]int{1, 2, 3, 4, 5} // 也可以这样写
fmt.Println(a)
a[0] = 200
a[1] = 300
fmt.Println(a)
fmt.Printf("这是a:%v\n",a)
fmt.Printf("这是a2:%#v\n",a)
}
func testArray5() {
//a := [5]int{1, 2, 3}
a := [5]int{3: 100, 4: 200} // 也可以这样写
fmt.Println(a)
a[0] = 200
a[1] = 300
fmt.Println(a)
}
func testArray7() {
a := [5]int{3: 100, 4: 200}
fmt.Println(a)
a[0] = 200
a[1] = 300
fmt.Println(a)
fmt.Printf("len(a)=%d\n", len(a))
/* var b [3]int
b = a // 报错 不同长度类型不能赋值 cannot use a (type [5]int) as type [3]int in assignment
fmt.Println(b)*/
var b [5]int
b = a
fmt.Println(b)
}
func testArray9() {
a := [5]int{3: 100, 4: 200}
fmt.Println(a)
var index,value int
for index,value = range a{
fmt.Printf("循环a[%d]=%d\n",index,value)
}
// 直接赋值
for index, value := range a {
fmt.Printf("a[%d]=%d\n", index, value)
}
// 不想要下标,就把下标忽略掉
for _, value := range a {
fmt.Printf("%d\n", value)
}
}
func testArray11() {
var a [3][2]int
a[0][0] = 10
a[0][1] = 28
a[1][0] = 30
a[1][1] = 32
a[2][0] = 35
a[2][1] = 38
fmt.Println(a)
for i := 0; i < 3; i++ {
for j := 0; j < 2; j++ {
fmt.Printf("%d ", a[i][j])
}
fmt.Println()
}
for i, val := range a {
fmt.Printf("row[%d]=%v\n", i, val)
for j, val2 := range val {
fmt.Printf("(%d,%d)=%d\n", i, j, val2)
}
fmt.Println()
}
}
func testArray12() {
a := [3]int{10, 20, 30}
fmt.Println(a)
b := a // 数组赋值是值类型,改变b中的不影响
b[0] = 100
a[1] = 1000
fmt.Printf("a=%v,b=%v\n", a, b)
}
func testArray13() {
var a int = 100
fmt.Println(a)
b := a
fmt.Printf("未修改a=%v,b=%v\n", a, b)
b = 1000
fmt.Printf("a=%v,b=%v\n", a, b)
}
func modify(b [3]int) {
b[0] = 120
}
func testArray14() {
var a [3]int = [3]int{10, 20, 30}
modify(a)
fmt.Println(a)
}
func main() {
//testArray1()
//testArray3()
//testArray5()
//testArray7()
//testArray9()
testArray11()
testArray12()
testArray13()
testArray14()
}
写入自己的博客中才能记得长久