Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 将nil[]字节变量转换为字符串';不要惊慌。为什么不呢?_Go - Fatal编程技术网

Go 将nil[]字节变量转换为字符串';不要惊慌。为什么不呢?

Go 将nil[]字节变量转换为字符串';不要惊慌。为什么不呢?,go,Go,因为片的零值(nil)的作用类似于零长度片。例如,您还可以声明一个切片变量,然后在循环中附加到该变量: package main import ("fmt") func main() { var bts []byte =nil fmt.Println("the result :", string(bts)) // why not panic ? // the result : } 更多细节可以在这里找到:一般来说,对于任何类型的nil您都可以生成任何您喜欢的字符串

因为片的零值(
nil
)的作用类似于零长度片。例如,您还可以声明一个切片变量,然后在循环中附加到该变量:

package main

import ("fmt")

func main() {

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

更多细节可以在这里找到:

一般来说,对于任何类型的
nil
您都可以生成任何您喜欢的字符串表示形式!这是因为在实现
fmt.Stringer
接口(请参阅)或任何类型上可以是
nil
的函数时,可以使用
nil
作为接收器值。换句话说,与OOP语言相比,您可以在
nil
对象上调用方法。在示例代码中,您将看到
ʕ◔ϖ◔嗨,尼洛用于第二种类型的
nil
值,但
BOO数据!!!::嗨!:)当您有一个元素在里面时(它只打印第一个元素作为示例代码)


再次请记住go中的
nil

语言规范的哪一部分指出这应该引起恐慌?相关:。您甚至可以切片一个nil切片,这真的很奇怪:
fmt.Printf(“wat:%v\n”,([]字节(nil))[0:0])
不会恐慌。
// 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
}