-2

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)

Redtakfeoh
  • 9
  • 1
  • 5

1 Answers1

1

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

Community
  • 1
  • 1
Amit Kumar Gupta
  • 17,184
  • 7
  • 46
  • 64