Suppose a function such as:
func returnNamedSlice(num int) (s []int)
I am able to do the following directly in the code, as if s was already made.
s = append(s, 5)
But if I don't do the above (append
operation), then s
is always nil
and the returned s
is also nil
.
Why this design? This seems very inconsistent.
CodePudding user response:
The following statement works because a nil slice is handled the same as an empty slice by the append
function.
s = append(s, 5)
Nil slices are handled the same as empty slices because the length and capacity of a nil slice are defined to be zero, the same as an empty slice.
The feature is unrelated to named return values. Here's a demonstration without return values:
var x []int // x is a nil slice of int
fmt.Println(x) // prints []
fmt.Println(x == nil) // prints true
x = append(x, 5) // x is slice with one element, 5
fmt.Println(x) // prints [5]
fmt.Println(x == nil) // prints false
A confusing point when examining these features is that the fmt
package prints nil slices and empty slices with the same representation, []
.
CodePudding user response:
You can append items to nil slice too, no matter it's nil or not.
Look at the example below:
package main
import "log"
func main() {
a := a() // no matter it returns nil
log.Println("Is a nil: ", a == nil)
a = append(a, 1) // you can append items to nil slice
log.Println(a)
//
b := b()
b = append(b, 2)
log.Println(b)
}
func a() (s []int) {
return
}
func b() (s []int) {
s = append(s, 5)
return
}
And the result:
2022/06/19 09:52:02 Is a nil: true
2022/06/19 09:52:02 [1]
2022/06/19 09:52:02 [5 2]