英文:
Behaviour of nil receiver in method in Golang
问题
package main
import (
"fmt"
)
type I interface {
M()
}
type T struct {
}
func (t *T) M() {
fmt.Println(t == nil)
}
func main() {
var i I
var t *T
i = t
fmt.Println(i == nil)
i.M()
}
结果是 false 和 true。
在两种情况下,值都是 nil,类型是 *main.T。
我理解在第一种情况下,i == nil 是 false,因为变量 i 没有 nil 类型。
我不理解为什么在方法 M() 内部,t == nil 是 true。
英文:
package main
import (
"fmt"
)
type I interface {
M()
}
type T struct {
}
func (t *T) M() {
fmt.Println(t == nil)
}
func main() {
var i I
var t *T
i = t
fmt.Println(i == nil)
i.M()
}
The result is false and true.
The value in both cases is nil and type is *main.T.
I understand that in the first case i == nil is false because the variable i does not have a nil type.
I do not understand why t == nil is true inside the method M().
答案1
得分: 8
在第一个情况下,i==nil是false,因为i是一个类型为T且值为nil的接口。要使接口等于字面值nil,它必须同时具有类型和值为nil。在这里,i具有非nil的类型。
在第二个情况下,接收器只是nil,因为函数M的接收器是一个类型为*T且值为nil的值。
英文:
In the first case, i==nil is false, because i is an interface whose type is T and whose value is nil. For an interface to be equal to the literal value nil, it has to have both type and value nil. Here, i has non-nil type.
In the second case, the receiver is simply nil, because the receiver of the function M is a value of type *T whose value is nil.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论