数组和列表

定义数组语法

1
2
3
var hens [6]int64

var hens := [...]string{""}

for-range 遍历

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package main

import (
	"fmt"
)

func main() {
	var hens [5]float64
	for i := 0; i < len(hens); i++ {
		fmt.Println(hens[i])
	}
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import (
	"fmt"
)

func main() {
	var hens [5]float64
	for i := 0; i < len(hens); i++ {
		fmt.Println(hens[i])
	}
	for idx, val := range hens {
		fmt.Printf("%v -> %+v\n", idx, val)
	}
}

map 的使用

map 是引用类型, 因此 不需要使用指针 也可以做

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import "fmt"

func main() {
	var mp map[int]string
	fmt.Println(mp == nil)
}
/*
PS D:\ASUS\Desktop\temp\golang学习> go run .\main.go
true

*/
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package main

import "fmt"

func main() {
	var mp map[int]string
	mp = make(map[int]string, 12)
	mp[1] = "hello world"
	fmt.Printf("%#v", mp)
}
/*
PS D:\ASUS\Desktop\temp\golang学习> go run .\main.go
map[int]string{1:"hello world"}
*/

map 的crud操作

  • delete 方法, 如果 key 存在,就删除 key-value ,若是不存在,也不会报错
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package main

import "fmt"

func main() {
	var mp map[int]string
	mp = make(map[int]string, 12)
	mp[1] = "hello"
	delete(mp, 1)
	fmt.Println(mp[1])
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import "fmt"

func main() {
	var mp map[int]string
	mp = make(map[int]string, 12)
	mp[1] = "hello"
	//	delete(mp, 1)
	fmt.Println(mp[1])

	for k := range mp {
		println(k)
		delete(mp, k)
	}
	fmt.Printf("%#v", mp)
}

map的查询操作

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package main

import "fmt"

func main() {
	var mp map[int]string
	mp = make(map[int]string, 12)
	mp[1] = "hello"
	//	delete(mp, 1)
	val, present := mp[1]
	if present {
		fmt.Printf("%v\n", val)
	}
}

map切片

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package main

import "fmt"

func main() {
	var mpList []map[int]string
	mpList = make([]map[int]string, 2)
	for i := 0; i < len(mpList); i++ {
		if mpList[i] == nil {
			mpList[i] = make(map[int]string)
		}
		mpList[i][1] = fmt.Sprintf("hello %#v \n", i)
	}
	fmt.Printf("%#v\n", mpList)

}

对 map 排序

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import (
	"fmt"
	"sort"
)

func main() {
	var mp map[int]string
	if mp == nil {
		mp = make(map[int]string)
	}

	mp[1] = "hello world"
	mp[55] = "abc"
	var list []int
	for k := range mp {
		list = append(list, k)
	}
	sort.Ints(list)
	fmt.Println(list)

}