Golang return nil

Brandon Hansen picture Brandon Hansen · Nov 11, 2014 · Viewed 10.2k times · Source

I am trying to wrap my head around Golang's types and interfaces but am struggling a bit to do so. Anyways, a common pattern that I see is func Whatever() (thing string, err error). I get how all of that works, but the one thing I am confused on is why it is ok to return "thing", nil. The specific instance that I am looking at is in revel here-

func (c *GorpController) Begin() revel.Result {
    txn, err := Dbm.Begin()
    if err != nil {
        panic(err)
    }
    c.Txn = txn
    return nil
}

revel.Result is an interface with this signature-

type Result interface {
    Apply(req *Request, resp *Response)
}

Anyways, I am just curious how returning nil satisfies the compiler in that occasion. Is there a resource that I can be pointed to for that?

Answer

VonC picture VonC · Nov 11, 2014

This is similar to returning a nil error: see "Why is my nil error value not equal to nil? "

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 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.

Here nil is the zero-value of the interface revel.Result.