文章目录
- 数组
- 切片
- 映射
数组
package mainimport "fmt"func main() {fmt.Println("array coding........")//var array [5]int//array[2] = 2//var array = [5]int{0, 1, 2, 3, 4}//array := [5]int{0, 1, 2, 3, 4}array := [...]int{0, 1, 2, 3, 4}//array := []int{1: 1, 3: 3} //[]中没有东西的是切片//a := 9//array := [5]*int{0: new(int)}//*array[0] = 10//array[1] = &afmt.Println(array)}
切片
package mainimport ("fmt"
)func main() {fmt.Println("slice coding........")//slice := make([]string, 3, 5)//slice[0] = "aaa"//slice := []int{10, 20, 30, 40, 50}//newSlice := slice[1:3] //长度为2,容量为4 两个切片共享内存//newSlice = append(newSlice, 60) //长度为3,容量为4 两个切片共享内存//slice := []int{10, 20, 30, 40, 50}//newSlice := append(slice, 60) //newSlice拥有全新的底层数组,容量变为原来的两倍,容量超过1000 按照1.25增长//source := []string{"aaa", "bbb", "ccc", "ddd", "eee"}//slice := source[2:3:4] //长度为1,容量为2 //slice := source[2:3:4] 长度为1,容量为3 [i:j:k]//好处:若 slice := source[2:3:3] append时会让slice有自己的底层数组,不会改变原有的切片//s1 := []int{1, 2}//s2 := []int{3, 4}//fmt.Println(append(s1, s2...)) //将一个切片追加到另一个切片//slice := []int{10, 20, 30, 40}//遍历一//for index, value := range slice { //range创建每个元素的副本,不是直接返回对该元素的引用// fmt.Printf("Index: %d , Value: %d\n", index, value)//}//遍历二//for _, value := range slice { // _忽略索引值// fmt.Printf("Value: %d\n", value)//}//遍历三 传统方式//for index := 0; index < len(slice); index++ {// fmt.Println(slice[index])//}}
映射
package mainimport ("fmt"
)func main() {fmt.Println("map coding........")//dict := make(map[string]int)dict := map[string]string{"a": "aaa", "b": "bbb"} //dict := map[string]string{}//dict := map[string][]string{}dict["c"] = "ccc"//方式一//value, exists := dict["a"]//if exists {// fmt.Println(value)//}//方式二//value := dict["b"]//if value != "" {// fmt.Println(value)//}delete(dict, "b")//map在函数间传递映射时,不会制造副本,函数修改map,所有对这个映射的引用都会察觉到这个修改fmt.Println(dict)
}