0%

为什么切片不用初始化

前言:不是都说 slice、map、channel 需要初始化才能使用吗?
为什么slice不用初始化就可以使用过呢?
让我们看以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
"fmt"
)

func main() {

// 可以使用
var s []string
s = append(s, "a")
fmt.Println(s)


// 未初始化不可使用
var m map[string]string
m["a"]= "b"
fmt.Println(m)

// 未初始化不可使用
var c chan string
go func() {
fmt.Println(<-c)
}()
c <- "a"
}

揭秘原因:

1
2
3
4
5
6
7
8
9
10
// The append built-in function appends elements to the end of a slice. If
// it has sufficient capacity, the destination is resliced to accommodate the
// new elements. If it does not, a new underlying array will be allocated.
// Append returns the updated slice. It is therefore necessary to store the
// result of append, often in the variable holding the slice itself:
// slice = append(slice, elem1, elem2)
// slice = append(slice, anotherSlice...)
// As a special case, it is legal to append a string to a byte slice, like this:
// slice = append([]byte("hello "), "world"...)
func append(slice []Type, elems ...Type) []Type

If it does not, a new underlying array will be allocated.

原来 apend() 方法回判断当前切片是否分配空间,如果为空则会进行初始化。