2014-11-11 4 views
2

Я пытаюсь обвести голову вокруг типов и интерфейсов Голанга, но я немного борюсь за это. В любом случае, общий шаблон, который я вижу, - func Whatever() (thing string, err error). Я понимаю, как все это работает, но единственное, с чем я смущен, - это то, что это нормально, return "thing", nil. Конкретный пример, который я смотрю в Ревеле здесь-Golang return nil

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

revel.Result интерфейс с этим signature-

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

В любом случае, я просто любопытно, как возвращение nil удовлетворяет компилятор в этом случае , Есть ли для этого ресурс, на который можно обратить внимание?

ответ

9

Это похоже на возвращении нулевой ошибки: см «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 .

Здесь nil является Нулевым значением интерфейса revel.Result.

+1

Perfect информация. Большое спасибо за это. Go - один из тех языков, который одновременно является самым легким и сложным языком, который я когда-либо изучал. –

+1

@BrandonHansen для получения дополнительной информации о интерфейсе: http://stackoverflow.com/a/23148998/6309. – VonC