package main
import ("fmt")
func main() {
var bts []byte =nil
fmt.Println("the result :", string(bts)) // why not panic ?
// the result :
}

- 191
- 1
- 1
- 6
-
Related: [nil slices vs non-nil slices vs empty slices in Go language](https://stackoverflow.com/questions/44305170/nil-slices-vs-non-nil-slices-vs-empty-slices-in-go-language/44305910#44305910). – icza Jun 09 '17 at 17:20
2 Answers
Because zero value of a slice (nil
) acts like a zero-length slice. E.g. you also can declare a slice variable and then append to it in a loop:
// Filter returns a new slice holding only
// the elements of s that satisfy f()
func Filter(s []int, fn func(int) bool) []int {
var p []int // == nil
for _, v := range s {
if fn(v) {
p = append(p, v)
}
}
return p
}
More details can be found here: https://blog.golang.org/go-slices-usage-and-internals

- 10,417
- 10
- 64
- 114
-
You can even slice a nil slice, which is really weird: `fmt.Printf("wat: %v\n", ([]byte(nil))[0:0])` does not panic. – Adrian Jun 09 '17 at 13:45
In general for any type that can be nil
you can generate whatever string representation you like! It's because when implementing fmt.Stringer
interface (see here) - or any function on a type that can be nil
- you can have a nil
for receiver value. In other words you can call methods on nil
objects in contrast with OOP languages. In this sample code, you'll see ʕ◔ϖ◔ʔ hey nilo!
for a nil
value of the second type, but BOO DATA!!! :: Hi! :)
when you have an element inside (it prints just the first element as a sample code).
And again keep in mind nil
is typed in go.

- 13,088
- 13
- 80
- 139