-3

I have a struct type named as game as follows:

type game struct {
    commands map[string]*command
    // ...
}

And I want to initialize a map in a struct of this type in the init function. I do it like this

func (game *game) init() {
    game.commands = make(map[string]*command)
    // ...
}

As I think, there is some code duplication. It would be neat if I could declare the type (map[string]*command) only once. Is there a way to do that? I tried to use reflect but it doesn't seem to work because make builtin takes a type and not a value.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
reflex0810
  • 908
  • 12
  • 13

2 Answers2

2

There is not a code duplication here. Code duplication is when you have multiple points in your code that does the same thing. That being said, you can leave your code like it is or you can use a Constructor, which has the benefit of restricting this initialization where you type is and is also a cleaner approach imho.

type game struct {
   commands map[string]*command
}

func game() *game {
   return &game{commands: make(map[string]*command)}
}

That way, when you need a game object, you can just do

gameObject := game()

and then use the map methods as you normally would (or you can also make a utility method just for that)

Jimi
  • 1,605
  • 1
  • 16
  • 33
  • 1
    But if you want to change the type of key, you will have to change it in your code twice. Isn't it a definition of code duplication? Why is my question so downvoted? – reflex0810 Feb 06 '20 at 10:01
  • Of course, when you change the type of something you HAVE to change all references to that. But this is NOT code duplication, is just how code works. Code duplication is, for instance, when you have both the type constructor and the init method that does the same thing, in this case initializing you map field. – Jimi Feb 06 '20 at 10:34
  • In such case you'll have two points in your code that does the same exact thing, so NOW you have some code duplication. But in this case you are NOT, because if you think code duplication is just when the same identifier exists multiple time in your code, than good luck writing a program! For instance, if you have two string variables, you have to write the word `string` twice. You think that this is code duplication? Spoiler alert: it isn't ;) – Jimi Feb 06 '20 at 10:35
2

If you are worried that repeating map[string]*command two times is duplication, you can define a new type from it.

type commandsMap map[string]*command

type game struct {
    commands commandsMap 
    // ...
}

func (game *game) init() {
    game.commands = make(commandsMap)
    // ...
}
Giulio Micheloni
  • 1,290
  • 11
  • 25