提交 5fd0977d 编写于 作者: _Fighter's avatar _Fighter

2021年12月7日

上级 c2f0ebfa
package main
import "fmt"
func printSlice(s []int) {
// cap 扩展是成倍增加
fmt.Printf("%d , len=%d,cap=%d\n", s, len(s), cap(s))
}
func main() {
var s []int //定义一个slice ,未赋值 Zero value for slice is nil
for i := 0; i < 100; i++ {
printSlice(s)
s = append(s, 2*i+1)
}
fmt.Println(s)
s1 := []int{2, 3, 4, 5, 6, 5, 7}
printSlice(s1)
sx := append(s1, 3, 4, 5) // 当前 s1 cap 长度为7 添加数据时长度*2 结果 cap=14
printSlice(sx)
//指定 len 长度的slice
s2 := make([]int, 16)
// 指定 len ,cap
s3 := make([]int, 10, 32)
printSlice(s2)
printSlice(s3)
fmt.Println("Copying slice")
// 把s1 copy 到 s2
copy(s2, s1)
printSlice(s2)
// go 是没有内建的 删除函数 ,只能手动删除
fmt.Println("deleting elements for slice")
// 当前 s2 的值为 [2 3 4 5 6 5 7 0 0 0 0 0 0 0 0 0] 删除 5,6 两个值
s2 = append(s2[:3], s2[5:]...) //可变长参数加...
printSlice(s2)
fmt.Println("Popping from front")
// 删除头
s2 = s2[1:]
// 删除尾
s2 = s2[:len(s2)-1]
printSlice(s2)
}
......@@ -57,4 +57,22 @@ func main() {
s2=[5 6], len(s2)=2 ,cap(s2)=3
*/
//添加元素时如果超越cap,系统会重新分配更大的层数组
// 由于值会传递关系,必须接收append的返回值
fmt.Println(" slice 相关操作方法")
op := []int{1, 2, 3, 4, 5, 6, 7, 9}
fmt.Println("op :", op)
t1 := op[2:6]
fmt.Println("t1:", t1)
t2 := append(t1, 10, 10)
fmt.Println("t2:", t2)
fmt.Println("op :", op) // 覆盖原数组数据,在 cap 以内的
//
}
func showLenCap(s []int) {
fmt.Printf("value:%s ,len(s)%d,cap(s)%d", s, len(s), cap(s))
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册