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

2021年12月6日

上级 80e4171a
package main
import "fmt"
func updateSlice(s []int) {
s[0] = 100
}
/*
slice 数据结构:
ptr 指向开头元素
len 当前slice 长度
cap 代表整个数组,是从ptr 指向的元素在结尾, slice 进行扩展时,不能超过cap
slice 可以向后扩展,不能向前扩展
s[x] 不可以超越len(s), 向后扩展不能超越低层数组cap(s)
*/
func main() {
arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7}
fmt.Println("arr[2:6] = ", arr[2:6])
fmt.Println("arr[:6] = ", arr[:6])
fmt.Println("s1 = ", arr[2:])
fmt.Println(" s2 = ", arr[:])
s1 := arr[2:]
s2 := arr[:]
updateSlice(s1)
fmt.Println(s1)
fmt.Println(arr)
updateSlice(s2)
fmt.Println(s2)
fmt.Println(arr)
fmt.Println("Reslice")
fmt.Println(s2)
s2 = s2[:5]
fmt.Println(s2)
s2 = s2[3:]
fmt.Println(s2)
fmt.Println(" extending slice")
arr[0], arr[2] = 0, 2
s1 = arr[2:6]
s2 = s1[3:5]
fmt.Println("arr=", arr)
fmt.Printf("s1=%v, len(s1)=%d ,cap(s1)=%d \n", s1, len(s1), cap(s1))
fmt.Printf("s2=%v, len(s2)=%d ,cap(s2)=%d \n", s2, len(s2), cap(s2))
fmt.Println(s1[3:6]) // 只在要cap 范围内,低层数组长度
/*
arr= [0 1 2 3 4 5 6 7]
s1=[2 3 4 5], len(s1)=4 ,cap(s1)=6
s2=[5 6], len(s2)=2 ,cap(s2)=3
*/
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册