英文:
Go-idiomatic naming of slice types
问题
当我需要在切片上使用方法时,我必须声明一个新类型。但是我应该给它取什么名字呢?
type SliceSomething []Something
还是 type SomethingSlice []Something
?
由于它被读作“某物的切片”,第一个选项似乎更好,但自动完成可能更喜欢第二个选项。
英文:
When I need methods on slices I have to declare a new type. But what should I name it?
type SliceSomething []Something
or type SomethingSlice []Something
?
Since it's read as "slice of something" the first one seems better, but autocomplete would probably prefer the second one.
答案1
得分: 3
> Go 中的变量名应该是短而不是长。
对于作用范围有限的局部变量尤其如此。
更喜欢 c
而不是 lineCount
。更喜欢 i
而不是 sliceIndex
。
> 基本规则是:离声明越远的地方使用的名称,名称就越需要描述性。
这就是为什么在 Go 源代码中很少找到 "Slice",除了以下几个例外:
encoding/gob/encoder_test.go:335: type recursiveSlice []recursiveSlice
encoding/json/encode_test.go:107: type renamedByteSlice []byte
encoding/json/encode_test.go:108: type renamedRenamedByteSlice []renamedByte
regexp/onepass.go:283: type runeSlice []rune
sort/sort.go:233: type IntSlice []int
sort/sort.go:243: type Float64Slice []float64
sort/sort.go:258: type StringSlice []string
unicode/maketables.go:1118: type runeSlice []rune
所以,如果你必须在名称中使用 "Slice",它应该是 type SomethingSlice []Something
而不是 type SliceSomething []Something
。
1: https://github.com/golang/go/wiki/CodeReviewComments
英文:
> Variable names in Go should be short rather than long.
This is especially true for local variables with limited scope.
Prefer c
to lineCount
. Prefer i
to sliceIndex
.
> The basic rule: the further from its declaration that a name is used, the more descriptive the name must be.
That is why you won't find "Slice
" often in the go sources, except in:
encoding/gob/encoder_test.go:335: type recursiveSlice []recursiveSlice
encoding/json/encode_test.go:107: type renamedByteSlice []byte
encoding/json/encode_test.go:108: type renamedRenamedByteSlice []renamedByte
regexp/onepass.go:283: type runeSlice []rune
sort/sort.go:233: type IntSlice []int
sort/sort.go:243: type Float64Slice []float64
sort/sort.go:258: type StringSlice []string
unicode/maketables.go:1118: type runeSlice []rune
So if you have to put 'Slice
' in the name, it would be type SomethingSlice []Something
rather than type SliceSomething []Something
.
1: https://github.com/golang/go/wiki/CodeReviewComments
答案2
得分: 0
请查看Go源代码以了解普遍认可的惯用法。
英文:
Check out Go source code for generally recognized idioms.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论