Go-idiomatic naming of slice types

╄→尐↘猪︶ㄣ 提交于 2021-02-07 10:46:20

问题


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:


The CodeReview wiki page

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.




回答2:


Check out Go source code for generally recognized idioms.



来源:https://stackoverflow.com/questions/27987392/go-idiomatic-naming-of-slice-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!