英文:
Convert nil []byte variable to string doesn't panic. Why not?
问题
以下是您提供的代码的中文翻译:
package main
import "fmt"
func main() {
var bts []byte = nil
fmt.Println("结果:", string(bts)) // 为什么不会引发 panic?
// 结果:
}
链接:https://play.golang.org/p/dzRzzKvUyd
英文:
package main
import ("fmt")
func main() {
var bts []byte =nil
fmt.Println("the result :", string(bts)) // why not panic ?
// the result :
}
答案1
得分: 2
因为切片的零值(nil
)的行为类似于零长度的切片。例如,您可以声明一个切片变量,然后在循环中向其追加元素:
// Filter 函数返回一个只包含满足 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
英文:
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
答案2
得分: 1
对于任何可以为nil
的类型,您可以生成任何您喜欢的字符串表示!这是因为当实现fmt.Stringer
接口(参见这里)或任何可以为nil
的类型上的任何函数时,您可以将接收器值设为nil
。换句话说,您可以在nil
对象上调用方法,与面向对象的编程语言相反。在这个示例代码中,当第二个类型的值为nil
时,您将看到ʕ◔ϖ◔ʔ hey nilo!
,但当您有一个元素时(它只打印第一个元素作为示例代码),它将打印BOO DATA!!! :: Hi! :)
。
请记住,在Go语言中,nil
是有类型的。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论