在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
//第一种声明方式 a := [10]int{} }
//第二种声明方式
slice与低产能数组的对应关系
package main import "fmt" func main() { a := []string{"a","b","c","d","e","f","g","h","i","j","k"} sa := a[2:5] fmt.Println(len(sa),cap(sa)) //3 9 sb := sa[1:3] //索引不能超过slice的cap值 fmt.Println(sb) } 注意:如果slice追加的元素超过slice容量,则内存地址发生变化,slice数组改变不再影响slice后的数组
Reslice
Append
Copypackage main import "fmt" func main() { s1 := []int{1,2,3,4,5} s2 := []int{6,7,8} copy(s1,s2) //s2为被拷贝元素,以短的slice为准,s1可以通过[:]来指定copy到的放置位置 fmt.Println(s1) //[6 7 8 4 5] }
map
package main import ( "fmt" ) func main() { a := make(map[int]string) //map初始化 a[1] = "ok" //增加键值对 delete(a ,1) //删除键为1的键值对 fmt.Println(a) //map[1:ok] var m map[int]map[int]string //键值都需初始化 m = make(map[int]map[int]string) //对key初始化 m[1] = make(map[int]string) //对每一个value初始化 m[1][1] = "a" n,ok := m[2][1] if !ok { m[2] = make(map[int]string) } m[2][1] = "GOOD" n,ok = m[2][1] fmt.Println(n,ok) //GOOD true }
//迭代操作 package main import ( "fmt" "sort" //排序 ) func main() { s := [3]string{"a","b","c"} for i,v:= range s{ fmt.Println(i,v) //0 a //1 b //2 c } sm := make([]map[int]string,5) for i := range sm{ sm[i] = make(map[int]string,1) sm[i][1] = "ok" fmt.Println(sm[i]) } fmt.Println(sm) m := map[int]string{1:"a",2:"b",3:"c",4:"d",5:"e"} ss := make([]int,len(m)) i := 0 for k,_ := range m{ ss[i] = k i ++ } sort.Ints(ss) //排序 fmt.Println(ss) }
|
请发表评论