golang小结 2
2018-02-05 本文已影响14人
TimeMage
array, slice, map
遍历
for k,v:=range m { //v可省
fmt.Println(k,v)
}
数组
-
一维数组定义
var arr1 = [4]int{1, 2, 3} var arr2 = [...]int{1, 2, 3} fmt.Printf("%T, %v, %d %d\n", arr1, arr1, len(arr1), cap(arr1)) fmt.Printf("%T, %v, %d %d\n", arr2, arr2, len(arr2), cap(arr2)) /* [4]int, [2 3 4 0], 4 4 [3]int, [1 2 3], 3 3 */
-
多维数组定义
var arr1 = [3][2]int{{1, 2}, {3, 4}, {5, 6}, } fmt.Println(arr1, len(arr1), len(arr1[0]) //[[1 2] [3 4] [5 6]] 3 2 )
-
注意事项
-
数组不能更改长度
//arr1 = append(arr1, 2) //arr1 = [5]int{3, 4, 5}
-
数组是值类型,赋值会进行完整拷贝
func foo(x [3]int, y []int) { fmt.Println(&x[0], &y[0]) } func test3() { arr1 := [...]int{1, 2, 3} fmt.Println(&arr1[0]) foo(arr1, arr1[:]) } //0xc042008440 //0xc042008480 0xc042008440
- 程序在运行时会自动对数组进行越界检查
-
切片
-
构造切片
var s1 []int = []int{1, 2} var s2 = make([]int, 10,20) var s3 = make([]int, 10) // make内置函数,是可重载的特例 make(type, len, cap=len) a := [...]int{1, 2, 3, 4, 5} var s4 = a[1:3] //切片名称的由来,底层数组相同 var s5 = append([]int{}, a[1:3]...)//底层数组不同,可变参数的使用
-
切片修改
//增加 s2 = append(s2,1) s2 = append(s2, s1...) //增加有可能会更换底层数组 //删除 index:=5 s2 = append(s2[:index],s2[index+1:]) //插入 r = append([]int,s2[index:]...)//必须重新分配个临时空间 s2 = append(s2[:index],123) s2 = append(s2, r...) //拷贝 copy(dst,src) 拷贝大小为两者len的最小值 func testcopy() { s1 := []int{1, 2, 3} s2 := []int{4, 5} copy(s1, s2) fmt.Println(s1) s1 = []int{7, 8, 9} copy(s2, s1) fmt.Println(s2) } /* [4 5 3] [7 8] */
-
注意事项
- 切片是引用类型。对切片内元素的更改,会对底层数组造成更改,对底层数组的更改,也会造成对切片元素的更改
- 对于同时使用底层数组,或切片共享底层数组时需特别注意
字典
func test1() {
a := map[string]int{"abc": 1,
"cda": 2,
}//构造
a["haha"] = 4//插入
delete(a, "abc")//删除
for k, _ := range a {//_可省
fmt.Println(k, a[k])
}
b := make(map[int]string, 2)// make(type, cap=0) 指定cap应该有所优化
b[3] = "good"
fmt.Println(b)
}
func test2() {
for i := 0; i < 5; i++ {
m := map[int]string{
0: "a", 1: "a", 2: "a", 3: "a", 4: "a",
5: "a", 6: "a", 7: "a", 8: "a", 9: "a",
}
fmt.Println(m)//map[int] 的实现方式不一定是有序的,每次遍历的结果可能不一样
for k := range m {
m[k+k] = "x"//插入或修改
delete(m, k)
}
fmt.Println(m)
}
}
/*
cda 2
haha 4
map[3:good]
map[1:a 3:a 5:a 9:a 0:a 2:a 4:a 6:a 7:a 8:a]
map[8:x 18:x 48:x 14:x 2:x 6:x 10:x 32:x]
map[0:a 5:a 6:a 7:a 9:a 1:a 2:a 3:a 4:a 8:a]
map[18:x 24:x 4:x 20:x 16:x 6:x 28:x]
map[1:a 2:a 4:a 6:a 0:a 5:a 7:a 8:a 9:a 3:a]
map[10:x 18:x 28:x 6:x 2:x 16:x 24:x]
map[0:a 2:a 5:a 8:a 1:a 3:a 4:a 6:a 7:a 9:a]
map[6:x 14:x 2:x 8:x 12:x 20:x 18:x 32:x]
map[8:a 9:a 0:a 3:a 6:a 5:a 7:a 1:a 2:a 4:a]
map[18:x 12:x 10:x 14:x 2:x 16:x]
*/