【发布时间】:2017-11-11 07:38:33
【问题描述】:
package main
import ("fmt")
func main() {
var bts []byte =nil
fmt.Println("the result :", string(bts)) // why not panic ?
// the result :
}
【问题讨论】:
标签: go
package main
import ("fmt")
func main() {
var bts []byte =nil
fmt.Println("the result :", string(bts)) // why not panic ?
// the result :
}
【问题讨论】:
标签: go
因为切片的零值 (nil) 的作用类似于零长度切片。例如。你也可以声明一个切片变量,然后在循环中附加到它:
// 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
}
更多详情可以在这里找到:https://blog.golang.org/go-slices-usage-and-internals
【讨论】:
fmt.Printf("wat: %v\n", ([]byte(nil))[0:0]) 并不恐慌。