golang nil, error and interface summary

interface{} and nil

The interface{} of golang can be roughly described as two elements (type+data), and the
interface will be equal to nil only when both type and data are nil.

var v *T
var i interface{}
i = v

v is a null pointer, so it must be equal to nil
interface{}, type and data are both nil, so they are also nil
but after i=v, the type of i is not nil, so it is not nil at this time

    var a interface{}
    fmt.Println(a == nil) //true
    a = "1" //data="1" type=string
    fmt.Println(a == nil) //false
    var b *int
    a = b //data=nil type=int
    fmt.Println(a == nil) //false
    fmt.Println(b == nil) //true
    fmt.Println(b == a) //true

Why is the equivalence between a, b and nil not transitive.
1. b==nil is correct. When a=b, a boxing operation is performed, and when a==b, an unboxing operation is performed
. 2. The conversion between type and interface in golang is not obvious. , easily misunderstood.

error

error is actually a special interface{}

type error interface {
    Error() string
}

example:

package main

import (
    "fmt"
)

type MyError struct {
    errCode uint8
}
func (e *MyError) Error() string {
    switch e.errCode {
    case 1:
        return "file not found"
    case 2:
        return "time out"
    case 3:
        return "permission denied"
    default:
        return "unknown error"
    }
}

// 相当于使用interface进行封箱操作
func GetError1() error {
    var err *MyError = nil
    return err
}

// 没有使用interface进行封箱操作
func GetError2() *MyError {
    var err *MyError = nil
    return err
}

func main() {
    ret1 := GetError1() //封箱,所以不为nil
    fmt.Println(ret1 == nil) //false
    e, _ := ret1.(*MyError) //显式拆箱,所以为nil
    fmt.Println(e == nil) //true

    ret2 := GetError2() // 不用转换,所以为nil
    fmt.Println(ret2 == nil) //true
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324650990&siteId=291194637