@@ -55,4 +55,61 @@ func appendValue(){
5555 fmt .Println ("appendlen:" ,cap (newSlice ),"slice" ,slice ,newSlice )
5656 fmt .Println ("增加容量" )
5757
58- }
58+ }
59+
60+ func threeSlice (){
61+ slice := []string {"Apple" ,"Orange" ,"Plum" ,"Bannane" ,"Grape" }
62+ //长度为1个元素 容量为2个元素
63+ newSlice := slice [2 :3 :4 ]
64+ //slice [i:j:k] 第一个表示开始的索引位置,
65+ //第二个表示索引位置加上元素的个数 1 结果是3 为了设置容量,
66+ //从索引位置开始 加上希望容量包含的元素个2 结果是4
67+ //长度j-i
68+ //容量k-i
69+ //容量大于已有容量会报错 就是超过原来的容量
70+ fmt .Println (newSlice )
71+ //panic: runtime error: slice bounds out of range
72+ // f :=slice[2:3:6]
73+ // fmt.Println(f)
74+ }
75+
76+ func sameLens (){
77+ source := []string {"Apple" ,"Orange" ,"Plum" ,"Bannane" ,"Grape" }
78+ slice := source [2 :3 :3 ]
79+ //长度和容量一样
80+ //现在长度和容量一致,还是共享着底层数组但是后面再进行append操作时创建新的数组
81+ slice = append (slice ,"232332" )//最佳字符串
82+ slice = append (slice ,"333" )//最佳字符串
83+
84+ s1 := []int {1 ,2 }
85+ s2 := []int {3 ,4 }
86+ fmt .Printf ("%v\n " ,append (s1 ,s2 ... ))
87+ for index , value := range slice {
88+ fmt .Printf ("Index:%d value :%s\n " ,index ,value )
89+ }
90+ for index ,value := range slice {
91+ fmt .Printf ("value %s vlaue-addr%X elemAddr %X\n " ,
92+ value ,& value ,& slice [index ])
93+ //range 返回的是副本 不是原始值 value 地址不变 要使用index 的方式访问
94+ }
95+ for _ ,val := range s1 {
96+ fmt.Printf ("value%d:" ,$val )
97+ }
98+
99+ for index := 1 ;index < len (slice );index ++ {
100+ fmt .Printf ("Index: %d Value :%d\n " ,index ,slice [index ])
101+ }
102+ }
103+
104+ func twoSlice (){
105+ slice := [][]int {{10 }, {100 ,200 }}
106+ slice [0 ] = append (slice [0 ],20 )
107+ //append 先增长切片 再将新的整型切片赋值为外发切片的第一个元素
108+ fmt .Println (slice )
109+ slice :make ([]int , le6 )
110+ newslice := foo (slice )
111+ fmt .Println (len (newslice ),cap (newslice ))
112+ }
113+ func foo (slice []int ) []int {
114+ return slice
115+ }//一个切片大小是24个字节 地址8个长度8容量8个字节
0 commit comments