空函数名在Go语言中是什么意思?

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

what does empty function name in go lang mean?

问题

第2行的代码是将route.Handler(req)的返回值赋给变量resproute.Handler(req)是调用route对象的Handler方法,并将req作为参数传递给该方法。根据代码的上下文,Handler方法可能返回一个响应对象。

第3行的代码是将resp.(NilResponse)的结果赋给变量nilresponseresp.(NilResponse)是一个类型断言,用于判断resp是否是NilResponse类型的实例。如果是,则nilresponse的值为true,否则为false

NilResponse是一个空结构体类型,它没有任何字段或方法。根据代码的上下文,可能是用于表示一个空的响应对象。

希望对你有帮助!

英文:

I am reading this code and I don't quite understand what line #2 does:

resp := route.Handler(req)
_, nilresponse := resp.(NilResponse)
if !nilresponse {

type NilResponse struct {
}

Thank you

答案1

得分: 1

这不是一个空的函数名,而是一个类型断言。它用于测试resp是否为NilResponse类型。如果是,nilResponse将为true,否则为false。这段代码通过使用_来丢弃结果的类型断言值。

参见类型断言

英文:

This isn't an empty function name. This is a type-assertion. It is testing that resp is a NilResponse. If it is, then nilResponse will be true, otherwise it will be false. This code throws away the resulting type-asserted value by using _.

See Type Assertions.

答案2

得分: 0

如果第二行是_, nilresponse := resp.(NilResponse),那么它根本不是一个函数调用,而是一个类型断言。代码的意思是“由resp表示的接口值是NilResponse类型的”。

编辑:不过你的赋值语句有点奇怪,因为第一个返回值应该是NilResponse对象,第二个返回值(如果指定了)是一个标志,用于指示它是否成功(或者可能是一个错误,我记不清是布尔值还是错误)。所以通常会是这样的:nilResponse, ok := 或者 nilResponse, err :=

英文:

If line two is _, nilresponse := resp.(NilResponse) then it's not a function call at all. It's a type assertion. The code is saying "the interface value represented by resp is of type NilResponse.

EDIT; your assignment is kind of odd though because the first return value would be the NilResponse object and the second (if specified) is a flag to indicate whether or not it worked (or maybe an error, can't remember if it's a bool or error). So typically it would be something like; nilResponse, ok := or nilResponse, err :=

huangapple
  • 本文由 发表于 2015年9月24日 05:37:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/32749949.html
匿名

发表评论

匿名网友

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

确定