这是一个块参数吗?

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

Is this a block argument?

问题

我最近开始学习Gin,在README文件中有以下代码:

v1 := router.Group("/v1")
{
    v1.POST("/login", loginEndpoint)
    v1.POST("/submit", submitEndpoint)
    v1.POST("/read", readEndpoint)
}

我查看了Group方法的源代码,如下所示:

IRouter interface {
    IRoutes
    Group(string, ...HandlerFunc) *RouterGroup
}

也许我对语法有误解或者在代码中漏掉了一些东西(我在Go方面还是新手),但是看起来它将一个代码块作为第二个参数传递进去,这在Go中是否可行?

英文:

I started learning Gin recently and in the README file comes the following code:

v1 := router.Group("/v1")
{
    v1.POST("/login", loginEndpoint)
    v1.POST("/submit", submitEndpoint)
    v1.POST("/read", readEndpoint)
}

I readed the source code for the method Group and is like this:

IRouter interface {
	IRoutes
	Group(string, ...HandlerFunc) *RouterGroup
}

Maybe I'm misunderstanding the syntaxis or missing something in the code (Im pretty new in Go) but it looks like it is passing a block as the second argument, is this possible in Go?

答案1

得分: 5

你在{ ... }中看到的是一个代码块,而不是任何参数。Group方法是可变参数的,可以接受任意数量的HandlerFunc参数,但在这里没有传入任何参数。

由于Go是块作用域的,你可以使用代码块来创建一个有限的变量作用域。由于块内没有声明,我认为在这里除了以组的形式缩进HandlerFunc赋值以外,没有其他用途。

下面是一个展示代码块作用域的示例:

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

x := 42

{
	x := 3
	y := 4
	fmt.Println("块内的 x:", x) // 输出 3
}

fmt.Println("块外的 x:", x) // 输出 42
// fmt.Println(y) // 报错: undefined: y
英文:

The block you see in { ... } is just that, a code block, not an argument to anything. The Group method is variadic, and could accept any number of HandlerFunc arguments, but nothing is passed in here.

Since Go is block scoped, you can use blocks to create a limited variable scope. Since there are no declarations within the blocks, I see no use for this pattern here other than to cause the HandlerFunc assignments to be indented as a group for style reasons.

An example showing the scope of a code block:

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

x := 42

{
	x := 3
	y := 4
	fmt.Println("x inside block:", x) // prints 3
}

fmt.Println("x outside block:", x) // prints 42
// fmt.Println(y) // undefined: y

答案2

得分: -1

IRouter的Group函数是一个可变参数函数。这意味着它可以接受任意数量的尾随参数,参数类型为HandlerFunc。

Go语言中另一个这种类型的函数的例子是fmt.Println

它的签名是:

func Println(a ...interface{}) (n int, err error)

因此,你可以使用可变数量的参数来调用它:

fmt.Println(1, 2)
fmt.Println("a", "b", "C")
英文:

The Group function of IRouter is a variadic function. It means it can be called with any number of trailing arguments, of type HandlerFunc.

Another example of this type of function in go is fmt.Println:

Its signature is:

func Println(a ...interface{}) (n int, err error)

so you can invoke it with a variable number of arguments:

fmt.Println(1, 2)
fmt.Println("a" , "b" , "C")

huangapple
  • 本文由 发表于 2016年1月9日 03:05:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/34684265.html
匿名

发表评论

匿名网友

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

确定