I won't say much nonsense, let's just read the code~
package main import ( "fmt" ) func main() { var s1 []int if s1 == nil { ("s1==nil") } else { ("s1!=nil") } var arr = [5]int{} s1 = arr[:] if s1 == nil { ("s1==nil") } else { ("s1!=nil") } }
Supplement: The difference between [golang]nil slice and empty slice
Preface
During development, you will encounter problems with nil slice and empty slice. Often, after declaring the slice, problems arise when using it.
question
The following is the wrong usage, which will report an error of the array's out-of-bounds, because it is just a slice declared, but it is not given an instantiated object. If this is a vector of cpp, it can be used directly, but golang cannot.
var slice []int
slice[1] = 0
At this time, the value of slice is nil. This situation can be used for functions that need to return slice. When an exception occurs, the function ensures that the function still has a return value of nil.
empty slice means that slice is not nil, but slice has no value, and the underlying space of slice is empty. The definition at this time is as follows:
slice := make([]int,0)//or
slice := []int{}
This is very useful when we query or process an empty list. It will tell us that the return is a list, but there is no value in the list.
In short, nil slice and empty slice are different things, and are distinguished in programming needs.
The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.