mirror of
https://gitee.com/shikong-sk/golang-study
synced 2025-04-20 10:18:05 +08:00
docs: Slice Append 切片 添加元素
This commit is contained in:
parent
41f6051df6
commit
7f4a72a154
51
base/slice/append/main.go
Normal file
51
base/slice/append/main.go
Normal file
@ -0,0 +1,51 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
s1 := []int{1, 3, 5, 7, 9}
|
||||
|
||||
fmt.Printf("s1 长度: %d, 容量: %d\t%+v\n", len(s1), cap(s1), s1)
|
||||
|
||||
// 调用 append 向切片追加元素
|
||||
// 需使用原来的变量接收 追加后的切片
|
||||
// 若 原切片内置容量不足时 会进行扩容 按规则新建一个扩容后的底层数组 复制数组后 再 添加元素
|
||||
// 若 新申请的容量 大于 2倍 旧容量 则 新申请的容量就为 新申请容量的大小
|
||||
// 若 旧切片的容量 小于 1024 则 新申请的容量 为 原来的 2倍
|
||||
// 若 旧切片的容量 大于等于 1024 则 新申请容量 为 旧容量 += 旧容量/4 循环递增 直到到 大于 新申请的容量
|
||||
|
||||
// src/runtime/slice.go 部分源码
|
||||
// newcap := old.cap
|
||||
// doublecap := newcap + newcap
|
||||
// if cap > doublecap {
|
||||
// newcap = cap
|
||||
// } else {
|
||||
// if old.cap < 1024 {
|
||||
// newcap = doublecap
|
||||
// } else {
|
||||
// // Check 0 < newcap to detect overflow
|
||||
// // and prevent an infinite loop.
|
||||
// for 0 < newcap && newcap < cap {
|
||||
// newcap += newcap / 4
|
||||
// }
|
||||
// // Set newcap to the requested cap when
|
||||
// // the newcap calculation overflowed.
|
||||
// if newcap <= 0 {
|
||||
// newcap = cap
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
s1 = append(s1, 11)
|
||||
|
||||
fmt.Printf("s1 长度: %d, 容量: %d\t%+v\n", len(s1), cap(s1), s1)
|
||||
|
||||
s2 := make([]int, 0, 1024)
|
||||
fmt.Printf("s2 长度: %d, 容量: %d\n", len(s2), cap(s2))
|
||||
|
||||
for i := 0; i < 1025; i++ {
|
||||
s2 = append(s2, 0)
|
||||
}
|
||||
|
||||
// 新容量 = 1024 + (1024/4) = 1280
|
||||
fmt.Printf("s2 长度: %d, 容量: %d\n", len(s2), cap(s2))
|
||||
}
|
Loading…
Reference in New Issue
Block a user