在Golang中,nil接收器在方法中的行为是什么?

huangapple go评论82阅读模式
英文:

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()
}

结果是 falsetrue

在两种情况下,值都是 nil,类型是 *main.T

我理解在第一种情况下,i == nilfalse,因为变量 i 没有 nil 类型。

我不理解为什么在方法 M() 内部,t == niltrue

英文:
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.

huangapple
  • 本文由 发表于 2021年9月30日 08:51:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/69384852.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定