底层数据结构
// SliceHeader is the runtime representation of a slice.
// It cannot be used safely or portably and its representation may
// change in a later release.
// Moreover, the Data field is not sufficient to guarantee the data
// it references will not be garbage collected, so programs must keep
// a separate, correctly typed pointer to the underlying data.
type SliceHeader struct {
Data uintptr
Len int
Cap int
}
概念
引用类型数据,传参、赋值时,是对slice数据结构的拷贝,不会拷贝底层的数组,
使用
增删改查
// 定义初始化
s := []int{1, 2, 3}
//在下标范围内,未初始化的都是该类型零值
s1 := []int{1: 5, 4: 10}
//make
s2 := make([]int, 3)
fmt.Println(s, "\n", s1, "\n", s2)
// 增
s = append(s, 4)
fmt.Println("增加", s)
// 删除
s = append(s[:0], s[1:]...)
fmt.Println("删除", s)
// 查
fmt.Println(s[0])
// 改
s[0] = 100
fmt.Println(s)
//输出
[1 2 3]
[0 5 0 0 10]
[0 0 0]
增加 [1 2 3 4]
删除 [2 3 4]
2
[100 3 4]
本文深入探讨了Go语言中切片(Slice)的底层数据结构及其操作方法,包括定义、初始化、增删改查等核心功能。通过具体代码示例,详细解释了如何利用切片进行高效的数据管理和操作。
904

被折叠的 条评论
为什么被折叠?



