英文:
Golang return nil
问题
我正在努力理解Golang的类型和接口,但有些困惑。无论如何,我经常看到的一个常见模式是func Whatever() (thing string, err error)。我知道这些都是如何工作的,但我对为什么可以return "thing", nil感到困惑。我正在查看的具体示例是在revel中的这个函数:
func (c *GorpController) Begin() revel.Result {
txn, err := Dbm.Begin()
if err != nil {
panic(err)
}
c.Txn = txn
return nil
}
revel.Result是一个具有以下签名的接口:
type Result interface {
Apply(req *Request, resp *Response)
}
无论如何,我只是好奇返回nil如何满足编译器的要求。有没有可以指导我的资源?
英文:
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?
答案1
得分: 12
这类似于返回一个空错误:参见"为什么我的空错误值不等于nil?"
在底层,接口由两个元素实现,一个是类型,一个是值。
值被称为接口的动态值,是一个任意的具体值,而类型则是该值的类型。对于
int值3,接口值包含(示意性地)(int, 3)。只有当内部值和类型都未设置时,接口值才为
nil,即(nil, nil)。特别地,nil接口将始终持有nil类型。
如果我们将类型为*int的指针存储在接口值中,无论指针的值如何,内部类型都将是*int,即(*int, nil)。
因此,即使内部指针为nil,这样的接口值也将是非nil的。
这里的nil是接口revel.Result的零值。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论