在 Go 中命名标签的标准做法是什么?

Go 规范Effective Go提供了命名包、类型、函数和变量的指南。还有一篇博客文章讨论了包名称。但是似乎没有一篇文章谈论与goto,break和一起使用的标签的命名约定continue

我认为最好的做法是完全避免使用标签,但是 Go 中这些控制流标签的标准约定是什么?

请注意,此问题不要求提供命名建议。我只是认为了解 Google 提供的有关它的指南或他们如何实际使用它会很好。


catspeake
浏览 106回答 1
1回答

喵喔喔

根据 Go 标准库和内部包的源代码,他们倾向于以与通常命名变量相同的方式命名标签。因此,标签可以包含大写或小写字符的任意组合,只要您不使用下划线书写任何内容即可。见https://golang.org/doc/effective_go.html#mixed-caps混合大写最后,Go 中的约定是使用MixedCapsormixedCaps而不是下划线来编写多字名称。一些例子:https://golang.org/src/cmd/internal/obj/x86/pcrelative_test.go#L102continue LOOPhttps://golang.org/src/compress/lzw/reader.go#L198break loophttps://golang.org/src/compress/flate/deflate.go#L402break Loophttps://golang.org/src/debug/gosym/symtab.go#L429break countloophttps://golang.org/src/encoding/csv/reader.go#L308break parseFieldhttps://golang.org/src/crypto/dsa/dsa.go#L128break GeneratePrimeshttps://golang.org/src/go/types/testdata/labels.srcfunc f3() {L1:L2:L3:&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; break L1 /* ERROR "invalid break label L1" */&nbsp; &nbsp; &nbsp; &nbsp; break L2 /* ERROR "invalid break label L2" */&nbsp; &nbsp; &nbsp; &nbsp; break L3&nbsp; &nbsp; &nbsp; &nbsp; continue L1 /* ERROR "invalid continue label L1" */&nbsp; &nbsp; &nbsp; &nbsp; continue L2 /* ERROR "invalid continue label L2" */&nbsp; &nbsp; &nbsp; &nbsp; continue L3&nbsp; &nbsp; &nbsp; &nbsp; goto L1&nbsp; &nbsp; &nbsp; &nbsp; goto L2&nbsp; &nbsp; &nbsp; &nbsp; goto L3&nbsp; &nbsp; }}Go 语言规范中的所有示例片段都将所有标签写入CamelCase. 这个词在规范和实现中Loop经常被缩写。Lhttps://golang.org/ref/spec#Break_statementsOuterLoop:&nbsp; &nbsp; for i = 0; i < n; i++ {&nbsp; &nbsp; &nbsp; &nbsp; for j = 0; j < m; j++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; switch a[i][j] {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case nil:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; state = Error&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break OuterLoop&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case item:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; state = Found&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break OuterLoop&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }https://golang.org/ref/spec#Continue_statementsRowLoop:&nbsp; &nbsp; for y, row := range rows {&nbsp; &nbsp; &nbsp; &nbsp; for x, data := range row {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if data == endOfRow {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue RowLoop&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row[x] = data + bias(x, y)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }https://golang.org/ref/spec#Goto_statementsgoto Error&nbsp; &nbsp; goto L&nbsp; // BAD&nbsp; &nbsp; v := 3L:if n%2 == 1 {&nbsp; &nbsp; goto L1}for n > 0 {&nbsp; &nbsp; f()&nbsp; &nbsp; n--L1:&nbsp; &nbsp; f()&nbsp; &nbsp; n--}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go