是否不鼓励在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.
例如,简单检查一个空字符串: p>
if s ==“” {返回0}
code> pre>
或者,一个for循环用-1预填充数组(我不认为 p>
for i:= range m {m [i] = -1}
code> pre>
\ n 即使这些功能完全非常简单,还是通常不鼓励这样做吗? 我并不是要学究,但通常会对此感到好奇。 p>
div>
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.