切片的三种定义
package main
import "fmt"
func main() {
//切片定义1
var slice []int //空切片
fmt.Println(slice) //打印结果 []
//追加元素
slice = append(slice, 1,2,3)
fmt.Println(len(slice))//长度 3
fmt.Println(cap(slice))//容量 4
//切片定义2
var s1 []int=[]int{1,2,3}
fmt.Println(s1) //打印结果 [1 2 3]
s2:=[]int{1,2,3}
fmt.Println(s2) //打印结果 [1 2 3]
//切片定义3
//make 函数 (切片,长度,容量)
//s :=make([]int,5,10)
s:=make([]int,5) //容量可以省略
fmt.Println(s) // 打印结果 [0 0 0 0 0]
s=append(s, 1,2,3,4,5)
fmt.Println(s) // 打印结果 [0 0 0 0 0 1 2 3 4 5]
s=append(s, 6,7,8)
fmt.Println(s) //打印结果 [0 0 0 0 0 1 2 3 4 5 6 7 8]
//在追加数据时长度超过容量,容量会自动扩容,一般是上一次容量x2 如果超过1024字节 每次扩容上一次1/4 容量扩容每次都是偶数
s11 :=make([]int,0,1)
oldcap:=cap(s11)
for i:=0;i<200000;i++{
s11=append(s11,i)
newcap:=cap(s11)
if oldcap<cap(s11){
fmt.Printf("cap:%d == %d\n",oldcap,newcap)
oldcap=newcap
}
}
//输出结果:
//cap:1 == 2
//cap:2 == 4
//cap:4 == 8
//cap:8 == 16
//cap:16 == 32
//cap:32 == 64
//cap:64 == 128
//cap:128 == 256
//cap:256 == 512
//cap:512 == 1024
//cap:1024 == 1280
//cap:1280 == 1696
//cap:1696 == 2304
//cap:2304 == 3072
//cap:3072 == 4096
//cap:4096 == 5120
//cap:5120 == 7168
//cap:7168 == 9216
//cap:9216 == 12288
//cap:12288 == 15360
//cap:15360 == 19456
//cap:19456 == 24576
//cap:24576 == 30720
//cap:30720 == 38912
//cap:38912 == 49152
//cap:49152 == 61440
//cap:61440 == 76800
//cap:76800 == 96256
//cap:96256 == 120832
//cap:120832 == 151552
//cap:151552 == 189440
//cap:189440 == 237568
//切片截取
section :=[]int{10,20,30,40,50}
// section[起始位置 low :结束位置(不包含) heigh:max]
// len = low-heigh
// cap = max-low
//newsection :=section[0:4:5]
//newsection :=section[0:4]
//newsection :=section[:4]
newsection :=section[2:]
newsection[2]=999//截取后的切片还是原始切片中的一块内容,所以修改后的切片影响原始切片
fmt.Println(section)
fmt.Println(newsection)
}
网友评论