[英]Why typeof(method) does not return reflect.Method instance?
Let's say I have Foo struct with a method defined as follows: 假设我有Foo结构,其方法定义如下:
type Foo struct {
Name string
}
func (f *Foo) Get(a int, b string) (string, error) {
return f.Name, nil
}
If I write 如果我写
obj := &Foo{}
t := reflect.TypeOf(obj.Get)
t.Kind()
returns reflect.Func
and apparently I have no way to access information that Get
func I extracted type information from "belongs" to the Foo
struct, that is receiver is of Foo
type, it is not even surfaced in the in-parameters. t.Kind()
返回reflect.Func
,显然我无法访问Get
func的信息,我从“所属”中提取了类型信息到Foo
结构,即接收器是Foo
类型,它甚至没有出现在α参数。
I guess that's intentional and I miss something fundamental about functions that made language authors throw away receiver information for typeof operations applied to method references. 我想这是故意的,我想念一些有关函数的基本知识,这些函数使语言作者丢弃了应用于方法引用的typeof操作的接收者信息。
I have two questions: 我有两个问题:
TypeOf
call above? TypeOf
调用来获取代码片段中的接收者类型吗? Trying to answer second question myself and based on what I see in the official documentation, it looks like my only options are to either pass TypeOf(receiver) and TypeOf(receiver.method) or TypeOf(receiver) and the name of the receiver's method. 尝试自己回答第二个问题,并根据我在官方文档中看到的内容,看来我唯一的选择是传递TypeOf(receiver)和TypeOf(receiver.method)或TypeOf(receiver)以及接收方的方法名称。
As mentioned by mkopriva, what you have is a method value : obj.Get
. 如mkopriva所述,您拥有的是方法值 :
obj.Get
。 And the method value is a function whose signature is identical to the method's without the receiver type: 方法值是一个函数,其签名与没有接收方类型的方法的签名相同:
If the expression
x
has static typeT
andM
is in the method set of typeT
,xM
is called a method value .如果表达式
x
具有静态类型T
和M
是在方法集合类型的T
,xM
称为方法值 。 The method valuexM
is a function value that is callable with the same arguments as a method call ofxM
.方法值
xM
是可以使用与xM
的方法调用相同的参数调用的函数值。 The expression x is evaluated and saved during the evaluation of the method value;在计算方法值期间对表达式x进行评估并保存; the saved copy is then used as the receiver in any calls, which may be executed later.
然后,保存的副本将在任何调用中用作接收者,以后可能会执行。
If you use a method expression (instead of a method value), the receiver type "shows" up in the parameter list (it's always the first): 如果使用方法表达式 (而不是方法值),则接收器类型将在参数列表中“显示”(始终是第一个):
fmt.Println(reflect.TypeOf((*Foo).Get))
Outputs (try it on the Go Playground ): 输出(在Go Playground上尝试):
func(*main.Foo, int, string) (string, error)
The method expression: 方法表达式:
If
M
is in the method set of typeT
,TM
is a function that is callable as a regular function with the same arguments asM
prefixed by an additional argument that is the receiver of the method .如果
M
在类型T
的方法集中 ,则TM
是可以作为常规函数调用的函数,该函数具有与M
相同的参数,并以作为方法的接收者的附加参数为前缀 。
See related questions: 查看相关问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.