小白请问go花括号什么情况 下可以写在一行?

taatcc · 2023-02-22 16:07:46 · 2392 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2023-02-22 16:07:46 的主题,其中的信息可能已经有所发展或是发生改变。

package main
import (

)

func main(){
a:=1
if a > 0 { return }
 }

比如 像上面 的 { return }就没报错。不是说要求 花括号换行么


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2392 次点击  
加入收藏 微博
7 回复  |  直到 2023-02-24 21:05:22
guokun1998
guokun1998 · #1 · 2年之前
func TestName(t *testing.T) {
    testF := func()
    {

    }

    if 1 == 1
    {

    }
}

go 不允许{换行写,例如上述的。}都可以。

这处的设计是基于 { 在其他语言中通常换行与不换行都行,go强制做了规定。

Neightly
Neightly · #2 · 2年之前
guokun1998guokun1998 #1 回复

```go func TestName(t *testing.T) { testF := func() { } if 1 == 1 { } } ``` go 不允许`{`换行写,例如上述的。`}`都可以。 这处的设计是基于 `{` 在其他语言中通常换行与不换行都行,go强制做了规定。

基础堪忧

dxx99
dxx99 · #3 · 2年之前
guokun1998guokun1998 #1 回复

```go func TestName(t *testing.T) { testF := func() { } if 1 == 1 { } } ``` go 不允许`{`换行写,例如上述的。`}`都可以。 这处的设计是基于 `{` 在其他语言中通常换行与不换行都行,go强制做了规定。

这不是编辑器在编译的时候会给每行结尾打上分号吗?如果是{结尾的话,就会跳过

Neightly
Neightly · #4 · 2年之前

One consequence of the semicolon insertion rules is that you cannot put the opening brace of a control structure (if, for, switch, or select) on the next line. If you do, a semicolon will be inserted before the brace, which could cause unwanted effects.

guokun1998
guokun1998 · #5 · 2年之前
NeightlyNeightly #4 回复

> One consequence of the semicolon insertion rules is that you cannot put the opening brace of a control structure (`if`, `for`, `switch`, or `select`) on the next line. If you do, a semicolon will be inserted before the brace, which could cause unwanted effects.

学到了,之前只知道是这么规定的,不知道原因。

Neightly
Neightly · #6 · 2年之前
guokun1998guokun1998 #5 回复

#4楼 @Neightly 学到了,之前只知道是这么规定的,不知道原因。

你还是没学到。从来就没有规定允许不允许,只有后果自负。举个简单的例子:

package main

func main() {
    sameLine()
    nextLine()
}

func sameLine() {
    switch alwaysFalse() {
    case true:
        println(true)
    case false:
        println(false)
    }
}

func nextLine() {
    switch alwaysFalse()
    {
    case true:
        println(true)
    case false:
        println(false)
    }
}

func alwaysFalse() bool {
    return false
}
wln123
wln123 · #7 · 2年之前

你可以当做花括号不能是每行的第一个字符

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传