0

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:

  1. the consts using iota
  2. the declaration of the struct type
  3. defining the struct implementation and typing in the values for each member.

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?

Jose
  • 1,389
  • 3
  • 16
  • 25
  • Some of your questions are addressed here: [Golang: Creating a Constant Type and Restricting the Type's Values](https://stackoverflow.com/questions/37385007/golang-creating-a-constant-type-and-restricting-the-types-values/37386119#37386119). – icza Oct 01 '18 at 11:16
  • Plus, if your type isn't exported, one cannot possibly create a new type of fruit and register it in the original package. – TDk Oct 01 '18 at 12:39

1 Answers1

1

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}
}
nilsocket
  • 1,441
  • 9
  • 17
  • Hej, thank's man. This code is certainly shorter. It also needs to declare every thing 3 times, however. I am wondering if can declare everything at once, or only twice. – Jose Oct 01 '18 at 13:36
  • @Jose Do you need to do any of this at all? Would not the list of constants suffice? – Michael Hampton Oct 01 '18 at 14:42
  • Because if we just define the constants, one coukd say ```basketball fruitType = 48``` but first, Basketball is an sport, not a fruit. And second, I do not have an implementation to peel Basketball, only know how to peel the fruits of my list – Jose Oct 01 '18 at 15:21