Go类型方法不等于实例方法

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

Go type method not equal to instance method

问题

为什么 T.set 不等于 t.set?
这背后的原理或翻译是什么?

在Go语言中,方法是与类型相关联的函数。当我们定义一个方法时,它与特定的类型相关联,并且只能通过该类型的实例来调用。在你提供的代码中,T 是一个结构体类型,而 t 是 T 类型的实例。

当你调用 t.Set() 方法时,它实际上是在调用 T 类型的 Set() 方法。这是因为方法是与类型相关联的,而不是与实例相关联的。因此,无论你使用哪个 T 类型的实例来调用 Set() 方法,实际上都是调用的 T 类型的 Set() 方法。

这就是为什么 T.Set 和 t.Set 的类型不同的原因。T.Set 的类型是 func(main.T, int),它接收一个 T 类型的实例作为接收者,而 t.Set 的类型是 func(int),它没有接收者。

你可以在这里查看代码的运行结果:http://play.golang.org/p/xYnWZ3PlyF

英文:
type T struct {
	Tp int
}

func (t T) Set(a int) {

	t.Tp = a
}
func main() {
	t := T{}
	fmt.Println(reflect.TypeOf(t.Set))
	fmt.Println(reflect.TypeOf(T.Set))
}

result :
func(int)
func(main.T, int)

why T.set is not equal to t.set?
what is principle or translation bebind this?

http://play.golang.org/p/xYnWZ3PlyF

答案1

得分: 3

t.Set是一个方法值。T.Set是一个方法表达式

方法值t.Set返回一个等效的函数:

func(a int) { t.Set(a) }

方法表达式T.Set返回一个将接收者作为第一个参数的函数。

func(t T, a int) { t.Set(a) }

这个示例演示了方法值和方法表达式之间的区别。

与关于方法表达式和方法值的讨论无关,函数Set应该使用指针接收者。否则,对t的更改将被丢弃。

func (t *T) Set(a int) {
   t.Tp = a
}

这是使用指针接收者的示例

英文:

t.Set is a method value. T.Set is a method expression.

The method value t.Set yields a function equivalent to:

func(a int) ( t.Set(a) }

The method expression T.Set yields a function that is equivalent to the method with the receiver as the first argument.

func(t T, a int) { t.Set(a) }

This playground example illustrates the difference between the method value and method expression.

Separate from this discussion about method expressions and method values,
the function Set should take a pointer receiver. Otherwise, the change to t is discarded.

func (t *T) Set(a int) {
   t.Tp = a
}

Here's the example with the pointer receiver.

huangapple
  • 本文由 发表于 2015年1月19日 00:54:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/28012287.html
匿名

发表评论

匿名网友

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

确定