Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang (*interface{})(nil) is nil or not?

Tags:

go

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?

like image 596
LeoTao Avatar asked Mar 28 '17 02:03

LeoTao


People also ask

What can be nil in Golang?

nil can represent zero values for several types like pointer types, map types, slice types, function types, channel types, interface types, and so on.

Is zero nil in Golang?

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.

Why does Golang use nil instead of null?

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.

Can pointers be nil Golang?

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.


1 Answers

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.

like image 175
zzn Avatar answered Sep 29 '22 05:09

zzn