Why is this?

81 views
Skip to first unread message

Josh Kamau

unread,
Apr 11, 2020, 9:54:05 AM4/11/20
to golang-nuts
package main

import (
"fmt"
)

func main() {

fmt.Println(isInputNil(nil)) //Returns true
fmt.Println(isMapNil(nil)) //Returns false
}

func isMapNil(m map[string]interface{}) bool {
return isInputNil(m)
}

func isInputNil(input interface{}) bool {
return input == nil
}

https://play.golang.org/p/bBSFSdnOOk4

Brian Candler

unread,
Apr 11, 2020, 10:21:34 AM4/11/20
to golang-nuts
You can think of an interface variable as a hidden struct: in pseudo-C, something like

struct {
    void *data;
    type_info *type;
}

If you assign a map to this (even a nil map), it still has a concrete type.  "data" is nil, but "type" is "map[X]Y"

Therefore the interface variable itself is not nil, as it now holds type info.

Maybe this helps:

Brian Candler

unread,
Apr 11, 2020, 10:26:46 AM4/11/20
to golang-nuts

Josh Kamau

unread,
Apr 11, 2020, 10:32:09 AM4/11/20
to Brian Candler, golang-nuts
Thanks Brian, That makes sense.  

Josh

On Sat, 11 Apr 2020 at 17:26, Brian Candler <b.ca...@pobox.com> wrote:

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/14f4a61e-40cd-488f-822f-1300d850f09f%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages