GoLang, what is contents in parenthesis before MethodName?

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

GoLang, what is contents in parenthesis before MethodName?

问题

(t *T)在MethodName之前的括号中的内容是方法的接收器(receiver)。在Go语言中,方法是与特定类型关联的函数。接收器指定了方法所属的类型,并且可以在方法内部访问该类型的字段和方法。在这个例子中,接收器是一个指向类型T的指针,表示该方法是与类型T关联的方法。

英文:
func (t *T) MethodName(argType T1, replyType *T2) error

what is contents in parenthesis before MethodName? I mean this (t *T)

This comes from here: http://golang.org/pkg/net/rpc/
I try to understand golang rpc and saw this method definition.

Thanks,

答案1

得分: 6

《Go编程语言规范》

方法声明

方法是带有接收器的函数。方法声明将标识符(方法名)绑定到一个方法,并将该方法与接收器的基本类型关联。

给定类型Point,以下声明

func (p *Point) Length() float64 {
	return math.Sqrt(p.x * p.x + p.y * p.y)
}

func (p *Point) Scale(factor float64) {
	p.x *= factor
	p.y *= factor
}

将方法Length和Scale与接收器类型*Point绑定到基本类型。

这是方法接收器。

英文:

> The Go Programming Language Specification
>
> Method declarations
>
> A method is a function with a receiver. A method declaration binds an
> identifier, the method name, to a method, and associates the method
> with the receiver's base type.
>
> Given type Point, the declarations

func (p *Point) Length() float64 {
	return math.Sqrt(p.x * p.x + p.y * p.y)
}

func (p *Point) Scale(factor float64) {
	p.x *= factor
	p.y *= factor
}

> bind the methods Length and Scale, with receiver type *Point, to the
> base type.

It's the method receiver.

huangapple
  • 本文由 发表于 2014年5月18日 10:23:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/23717962.html
匿名

发表评论

匿名网友

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

确定