-4

I have two variables:

somethingA := 123
somethingB := 456

This two variables are filled though the system and lets presume that you have third variable:

type := "A"

With third variable you want to call somethingA but not like following:

if type == "A" {
    return somethingA
}else{
    return somethingB
}

but something like:

return something{type}

Is something like this possible in go?

Thank you

iWizard
  • 6,816
  • 19
  • 67
  • 103
  • Just a heads up: type is keyword in go. so you cant name your variable that way. – sieberts Nov 05 '18 at 20:26
  • I'm not sure what your example is asking, something like these questions? https://stackoverflow.com/questions/26566124/golang-variable-with-type-from-string, https://stackoverflow.com/questions/10210188/instance-new-type-golang, https://stackoverflow.com/questions/23030884/is-there-a-way-to-create-an-instance-of-a-struct-from-a-string, etc. – JimB Nov 05 '18 at 20:32
  • Please who has downvoted my question let explain here what is reason for that. – iWizard Nov 05 '18 at 20:37
  • @JimB - for exampel you have to arrays and sou want to go over for loop but one of them. Over my upper way you can only write two loops which is really not nice. It would be nice to pass array name if that is possible and then do loop. – iWizard Nov 05 '18 at 20:38

2 Answers2

4

use a map

package main

import (
    "fmt"
)

func main() {
        x:=make(map[string]int)
        x["SomethingA"]=123
        x["SomethingB"]=456
    fmt.Println(x["SomethingA"])
    fmt.Println(x["SomethingB"])
}
Vorsprung
  • 32,923
  • 5
  • 39
  • 63
2

Is something like this possible in go?

No.

All ways to do something like this boils down to the solution you showed.

Volker
  • 40,468
  • 7
  • 81
  • 87
  • Except using a map, which doesn't require any conditionals. – Adrian Nov 06 '18 at 15:27
  • @Adrian The map just _hides_ the conditionals. – Volker Nov 06 '18 at 17:16
  • Not exactly. While there are certainly branches involved in the implementation of maps, it is not the same implementation at all. It is a completely different implementation based on a hash table. – Adrian Nov 06 '18 at 17:22