douan1893 2016-01-08 19:05
浏览 4
已采纳

这是一个块参数吗?

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?

  • 写回答

2条回答 默认 最新

  • dpbyr64224 2016-01-08 19:16
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 quartz框架,No record found for selection of Trigger with key
  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数
  • ¥15 关于#线性回归#的问题:【统计】回归系数要转化为相关系数才能进行Fisher' Z转化吗(相关搜索:回归模型)
  • ¥100 使用matlab解决含分段变量的优化问题
  • ¥15 matlab基于鲸鱼算法优化vmd
  • ¥20 PCB设计与制作问答
  • ¥20 课堂跑如何下载ppt