14.数组
数组定义以及初始化
数组是同一类型的元素集合(这和python不一样)。下面是定义一个数组,整数数组的元素默认初始化为0,字符串数组中的元素默认初始化为"",浮点型为0.0
1: var a [3]int2: a[0]=103: a[1]=204: a[2]=305: //另几种数组初始化
6: var a [3]int = [3]int{10, 20, 30}7: a := [3]int{10,20,30}8: a := [...]int{10,20,30} //固定三个点
9: a := [3]int{10}10: a := [3]int{2:10} // 2是10的下标
len(a)返回数组的长度
带索引的数组遍历
1: var index, val int
2: for index, val := range a {
3: }
另一种遍历
1: var a [5]int = [5]int {1, 3, 5, 8, 7}
2: func main() {
3: sum := 0
4: for _, val := range a {
5: sum += val
6: }
7: fmt.Println(sum)
8: }
二维数组
1: for i, val := range a{
2: for j,val_2 := range val {
3: //
4: }
5: }
数组拷贝和传参
1: var a [3]int
2: a[0] = 10
3: a[1] = 20
4: a[2] = 30
1: func main(){
2: b:=a
3: b[0]= 1000
4: fmt.Println(a, b)
5: }
6: >>> [1000 20 30] [1000 20 30]
7: // 可以看出来这里是类似python里的深拷贝
另外一种
1: func main() {
2: var a []int = []int{10, 20, 30}
3: modify(a)
4: fmt.Println(a, b)
5: }
6: func modify(b []int) {
7: b[0] = 1000
8: return
9: }
结果
1: >>> [1000 20 30]
练习:
1.求数组所有元素之和
1: var a [3]int = [3]int{10, 20, 30}
2: func main() {
3: sum := 0
4: for i:=0; i<len(a);i++ {
5: sum += a[i]
6: }
7: fmt.Println(sum)
8: }
2.找出数组中和为给定值的两个元素的下标,比如数组:[1,3,5,8,7],找出两个元素之和等于8的下标分别是(0, 4)和(1, 2)
常规写法:
1: var a [5]int = [5]int {1, 3, 5, 8, 7}
2: func main() {
3: for i:=0; i<len(a); i++ {
4: for j:=i+1; j<len(a)-i; j++{
5: if a[i]+a[j] == 8 {
6: fmt.Println(i, j)
7: }
8: }
9: }
10: }