这是一个块参数吗? [英] Is this a block argument?

查看:92
本文介绍了这是一个块参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习杜松子酒,并在 README 文件包含以下代码:

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

我参考了源代码的方法<
$ b

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

也许我误解了语法或者在代码中丢失了某些东西(在Go中我很新),但它看起来像是在传递一个块作为第二个参数,这在G中是可能的在 {...} 中看到的块,就是这样,一个代码块,而不是任何参数。 Group 方法是可变的,并且可以接受任意数量的 HandlerFunc 参数,但是这里没有任何内容被传入。

由于Go是块范围,您可以使用块创建一个有限的变量范围。由于块内没有声明,因此除了使 HandlerFunc 赋值由于样式原因缩进为一个组之外,我看不到这种模式。



一个显示代码块范围的例子:

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

  x:= 42 

{
x:= 3
y:= 4
fmt.Println(x inside block:,x) //打印3


fmt.Println(x outside block:,x)//打印42
// fmt.Println(y)// undefined: y


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?

解决方案

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

这篇关于这是一个块参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆