interface with the interface value of nil-nil go Trap

go to interfaces {} is not a pointer, though it looks like a pointer.
When the interface {} and its type, when values are nil, the value was nil ==
Consider the following program

package main
import "fmt"
func main() {  
    var data *byte
    var in interface{}
    fmt.Println(data,data == nil) //prints: <nil> true
    fmt.Println(in,in == nil)     //prints: <nil> true
    in = data
    fmt.Println(in,in == nil)     //prints: <nil> false
    //'data' is 'nil', but 'in' is not 'nil'
}

The above is an example of that.
The following are problems that may be encountered in the development of
error Demonstration:

import "fmt"
func main() {  
    doit := func(arg int) interface{} {
        var result *struct{} = nil
        if(arg > 0) {
            result = &struct{}{}
        }
        return result
    }
    if res := doit(-1); res != nil {
        fmt.Println("good result:",res) //prints: good result: <nil>
        //'res' is not 'nil', but its value is 'nil'
    }
}

Correct demonstration:

package main
import "fmt"

func main() {  
    doit := func(arg int) interface{} {
        var result *struct{} = nil
        if(arg > 0) {
            result = &struct{}{}
        } else {
            return nil //return an explicit 'nil'
        }
        return result
    }
    if res := doit(-1); res != nil {
        fmt.Println("good result:",res)
    } else {
        fmt.Println("bad result (res is nil)") //here as expected
    }
}

I see a wrong use case

func Foo() error {
    var err *os.PathError = nil
    // …
    return err
}

func main() {
    err := Foo()
    fmt.Println(err)        // <nil>
    fmt.Println(err == nil) // false
}

Reproduced in: https: //www.jianshu.com/p/cc111876ac83

Guess you like

Origin blog.csdn.net/weixin_34124939/article/details/91131200