len and cpacity
The length of a slice is the number of elements it contains.
The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.
SliceHeader
/src/reflect/value.go
// 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
}
func Append(s Value, x ...Value) Value {
s.mustBe(Slice)
s, i0, i1 := grow(s, len(x))
for i, j := i0, 0; i < i1; i, j = i+1, j+1 {
s.Index(i).Set(x[j])
}
return s
}
func grow(s Value, extra int) (Value, int, int) {
i0 := s.Len()
i1 := i0 + extra
if i1 < i0 {
panic("reflect.Append: slice overflow")
}
m := s.Cap()
if i1 <= m {
return s.Slice(0, i1), i0, i1
}
if m == 0 {
m = extra
} else {
const threshold = 256
for m < i1 {
if i0 < threshold {
m += m
} else {
m += (m + 3*threshold) / 4
}
}
}
t := MakeSlice(s.Type(), i1, m)
Copy(t, s)
return t, i0, i1
}
创建slice
下标
通过下标的方式获得数组或者切片的一部分;
使用下标初始化切片不会拷贝原数组或者原切片中的数据,它只会创建一个指向原数组的切片结构体,所以修改新切片的数据也会修改原切片。
字面量
s :=[] int {1,2,3 }
make
使用关键字 make 创建切片:make([]T, length, capacity)
(len 是数组的长度并且也是切片的初始长度, capacity 为容量,len指向的单元格会初始化为0值)
为什么需要capacity?因为扩容会触发拷贝,指定capacity能一定程度上避免扩容,提升性能
var 声明 后 赋值
var slice1 []int
slice1[0] = 1
创建定长数组
balance := [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}
var balance [5]float32
balance[0] = 1000.0