douyi2107 2016-12-02 07:56
浏览 42
已采纳

类型声明在golang中的重要性,nil值[重复]

This question already has an answer here:

I have this small golang test I cannot understand:

package main

import "fmt"

type myObj struct {
}

func nilObj() *myObj {
    return nil
}

func nilInt() interface{} {
    return nil
}

func main() {
    var obj1 interface{}
    fmt.Println(obj1 == nil)    // true
    obj1 = nilObj()
    fmt.Println(obj1 == nil)    // false

    var obj2 *myObj
    fmt.Println(obj2 == nil)    // true
    obj2 = nilObj()
    fmt.Println(obj2 == nil)    // true

    var obj3 interface{}
    fmt.Println(obj3 == nil)    // true
    obj3 = nilInt()
    fmt.Println(obj3 == nil)    // true
}

Between obj1 and obj2, only the variable declaration changes, but the result is different.

Between obj1 and obj3, the function call does not return the same type (struct pointer vs interface). I am not entirely sure I understand the result.

Any help is welcome (https://play.golang.org/p/JcjsJ-_S8I)

</div>
  • 写回答

1条回答 默认 最新

  • doukougua7873 2016-12-02 08:09
    关注

    Under the covers, interfaces are implemented as two elements, a type and a value. The value, called the interface's dynamic value, is an arbitrary concrete value and the type is that of the value. For the int value 3, an interface value contains, schematically, (int, 3).

    An interface value is nil only if the inner value and type are both unset, (nil, nil). In particular, a nil interface will always hold a nil type. If we store a nil pointer of type *int inside an interface value, the inner type will be *int regardless of the value of the pointer: (*int, nil). Such an interface value will therefore be non-nil even when the pointer inside is nil.

    https://golang.org/doc/faq#nil_error

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?