Drathier
Drathier

Reputation: 14539

Go-idiomatic naming of slice types

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.

Upvotes: 1

Views: 1131

Answers (2)

Martin Drlík
Martin Drlík

Reputation: 1464

Check out Go source code for generally recognized idioms.

Upvotes: 0

VonC
VonC

Reputation: 1328122

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.

Upvotes: 3

Related Questions