douwan7382
douwan7382
2016-07-08 21:07

为什么fmt允许使用空括号?

  • IT行业问题
  • 计算机技术
  • it技术
  • 编程语言问答
  • 互联网问答
已采纳

I was just wondering why these brackets haven't been removed after running go fmt, does their use have a function?

package main

import "fmt"

func main() {

    fmt.Println("Hello, 世界")

    {
        {
            {

            }

        }
    }
}

Example here, thanks.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongmei2002 dongmei2002 5年前

    Brackets on their own denote code Blocks. From the spec:

    A block is a possibly empty sequence of declarations and statements within matching brace brackets.

    These are part of the Go syntax, and go fmt formats them according the its formatting rules.

    点赞 评论 复制链接分享
  • duanmaifu3428 duanmaifu3428 5年前

    They basically function like an internal namespace, so any definition(s) you put in between an encapsulating brace will not be visible outside of it.

    // ... other code above ...
    
    {
      a := 5 // declare a
    }
    
    a = 5 // compiler error, a is undeclared
    

    And plus formatting tools such as gofmt or autopep8 (for python) do not modify a given file beyond adding/removing whitespace or newline characters to already existing code.

    点赞 评论 复制链接分享

为你推荐