Suppose I have the following snippet in my package:
package fruits
type fruitType uint8
const(
banana fruitType = iota
apple fruitType = iota
strawberry fruitType = iota
)
type allFruitTypes struct {
Banana fruitType
Apple fruitType
Strawberry fruitType
}
var allFruitTypesImpl = allFruitTypes {
Banana: banana,
Apple: apple,
Strawberry: strawberry,
}
//GetAllFruitTypes returns a list with all the possible fruit types
func GetAllFruitTypes() *allFruitTypes {
return &allFruitTypesImpl
}
In this way, I can avoid that outside my package new types of fruits are created. And still it allows to read my list of possible fruit types. Is that correct?
So my main problem in here is that I find really annoying to define 3 things that mean the same:
For me, semantically the three of them mean the same. However, because of the way go works (or my lack of knowledge on how to type this better in go) I have to retype the same thing 3 times.
Is there any way to cause the same effect without having to type down the very same semantics 3 times?
This is the shortest:
//FruitTypes has a field for every fruit type
type FruitTypes struct {
Banana, Apple, Strawberry uint8
}
//Fruits returns a list with all the possible fruit types
func Fruits() *FruitTypes {
return &FruitTypes{0, 1, 2}
}
If you need constants
const (
banana uint8 = iota
apple
strawberry
)
//FruitTypes has a field for every fruit type
type FruitTypes struct {
Banana, Apple, Strawberry uint8
}
//Fruits returns a list with all the possible fruit types
func Fruits() *FruitTypes {
return &FruitTypes{banana, apple, strawberry}
}