duadlkc5762218 2018-09-18 07:42
浏览 22
已采纳

是否不鼓励在Go中使用单线for循环或if语句?

For example, a simple check for an empty string:

if s == "" { return 0 }

Or, a for-loop to pre-fill an array with -1 (I don't think there's an easier way to do this):

for i := range m { m[i] = -1 }

Is this generally discouraged, even if these functions are extremely simple altogether? I don't mean to be pedantic, but am generally curious what the sentiment for this is.

  • 写回答

1条回答 默认 最新

  • douchi2022 2018-09-18 07:48
    关注

    Generally, the culture in Go is to format your code the way the command go fmt would format it. (The reasons why there is an accepted style are in the linked article.)

    To the extent that go fmt puts structured statement bodies on separate lines means that yes, the practice is "discouraged" in the community, but only because of a desire to have a common look for as much Go source code as possible.

    The reasons why one-liners are not part of go fmt are not as relevant as the fact that go fmt was chosen as the canonical style. If you wish to argue about the pros and cons of one-liners, you can look at the debates made in just about any curly-brace language, as they are not unique to Go. Of course, Go's mandating of braces does make the question slightly different than, say, C or Java, where unbraced bodies means it's harder to "add a new statement in the body," but basically many of the same arguments for readability do apply.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站