将 nil []byte 变量转换为字符串不会引发恐慌。为什么呢?

huangapple go评论76阅读模式
英文:

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 :
}

https://play.golang.org/p/dzRzzKvUyd

答案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.

huangapple
  • 本文由 发表于 2017年6月9日 18:16:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/44455197.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定