Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert nil []byte variable to string doesn't panic. Why not?

Tags:

go

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

like image 297
cdh0805010118 Avatar asked Jun 07 '26 17:06

cdh0805010118


1 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

like image 82
Dmitry Frank Avatar answered Jun 10 '26 02:06

Dmitry Frank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!