1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| slice -> append & copy map -> delete
// 向切片中添加元素并打印出切片的长度和容量 func main() { appendElementForSlice() }
func appendElementForSlice() { mIDSlice := make([]string, 2) mIDSlice[0] = "id-1" mIDSlice[1] = "id-2" fmt.Println("len=",len(mIDSlice)) fmt.Println("cap=",cap(mIDSlice)) mIDSlice = append(mIDSlice, "id-3") fmt.Println(mIDSlice) fmt.Println("After len=",len(mIDSlice)) fmt.Println("After cap=",cap(mIDSlice)) }
程序执行结果: len= 2 cap= 2 [id-1 id-2 id-3] After len= 3 After cap= 4
// 拷贝切片 test 1 func main() { copyForSlice() }
func copyForSlice() { mIDSliceDst := make([]string, 2) mIDSliceDst[0] = "id-dst-1" mIDSliceDst[1] = "id-dst-2"
mIDSliceSrc := make([]string, 2) mIDSliceSrc[0] = "id-src-1" mIDSliceSrc[1] = "id-src-2"
copy(mIDSliceDst, mIDSliceSrc) fmt.Println(mIDSliceDst) }
程序执行结果: [id-src-1 id-src-2]
// 拷贝切片 test 2 func main() { copyForSlice() }
func copyForSlice() { mIDSliceDst := make([]string, 3) mIDSliceDst[0] = "id-dst-1" mIDSliceDst[1] = "id-dst-2" mIDSliceDst[2] = "id-dst-3"
mIDSliceSrc := make([]string, 2) mIDSliceSrc[0] = "id-src-1" mIDSliceSrc[1] = "id-src-2"
copy(mIDSliceDst, mIDSliceSrc) fmt.Println(mIDSliceDst) }
程序执行结果: [id-src-1 id-src-2 id-dst-3]
// 拷贝切片 test 3 func main() { copyForSlice() }
// 拷贝切片 func copyForSlice() { mIDSliceDst := make([]string, 2) mIDSliceDst[0] = "id-dst-1" mIDSliceDst[1] = "id-dst-2"
mIDSliceSrc := make([]string, 3) mIDSliceSrc[0] = "id-src-1" mIDSliceSrc[1] = "id-src-2"
copy(mIDSliceDst, mIDSliceSrc) fmt.Println(mIDSliceDst) }
程序执行结果: [id-src-1 id-src-2]
说明copy操作不会为mIDSliceDst扩容
// delete test 1 func main() { deleteFormMap() }
func deleteFormMap() { mIDMap := make(map[int]string) mIDMap[0] = "id-1" mIDMap[1] = "id-2" delete(mIDMap, 0) fmt.Println(mIDMap) }
程序执行结果: map[1:id-2]
|