golang-slice-从底层到使用

本文深入探讨了Go语言中切片(Slice)的底层数据结构及其操作方法,包括定义、初始化、增删改查等核心功能。通过具体代码示例,详细解释了如何利用切片进行高效的数据管理和操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

底层数据结构

// 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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值