Hiding nil values, understanding why golang fails here

后端 未结 3 494
青春惊慌失措
青春惊慌失措 2020-11-22 11:16

I fail to understand how to correctly assure that something is not nil in this case:

package main

type shower interface {
  getWater() []shower         


        
3条回答
  •  春和景丽
    2020-11-22 12:02

    Let's think of an interface as a pointer.

    Say you have a pointer a and it's nil, pointing to nothing.

    var a *int // nil
    

    Then you have a pointer b and it's pointing to a.

    var b **int
    b = &a // not nil
    

    See what happened? b points to a pointer that points to nothing. So even if it's a nil pointer at the end of the chain, b does point to something - it isn't nil.

    If you'd peek at the process' memory, it might look like this:

    address | name | value
    1000000 | a    | 0
    2000000 | b    | 1000000
    

    See? a is pointing to address 0 (which means it's nil), and b is pointing to the address of a (1000000).

    The same applies to interfaces (except that they look a bit different in memory).

    Like a pointer, an interface pointing to a nil pointer would not be nil itself.

    Here, see for yourself how this works with pointers and how it works with interfaces.

提交回复
热议问题