the code snippet is the following:
package main
import (
"fmt"
"reflect"
)
func main() {
a := (*interface{})(nil)
fmt.Println(reflect.TypeOf(a), reflect.ValueOf(a))
var b interface{} = (*interface{})(nil)
fmt.Println(reflect.TypeOf(b), reflect.ValueOf(b))
fmt.Println(a == nil, b == nil)
}
the output like below:
*interface {} <nil>
*interface {} <nil>
true false
so var interface{}
is different from :=
,why?
nil can represent zero values for several types like pointer types, map types, slice types, function types, channel types, interface types, and so on.
Nil represents a zero value in Golang. As you may already know, zero values are the "default" value for defined variables in Go. This means that some types doesn't cannot hold empty values, instead acquiring zero values upon initialization to get rid of the problem of checking values for emptyness.
nil is a frequently used and important predeclared identifier in Go. It is the literal representation of zero values of many kinds of types. Many new Go programmers with experiences of some other popular languages may view nil as the counterpart of null (or NULL ) in other languages.
Nil Pointers All variables in Go have a zero value. This is true even for a pointer. If you declare a pointer to a type, but assign no value, the zero value will be nil . nil is a way to say that “nothing has been initialized” for the variable.
according to golang faq
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.
a := (*interface{})(nil)
is equal with var a *interface{} = nil
.
but var b interface{} = (*interface{})(nil)
, mean b
is type interface{}
, and interface{}
variable only nil
when it's type and value are both nil
, obviously type *interface{}
is not nil
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With