Reputation: 315
I have defined a constant with a type. I want to use the value of a variable to refer to the constant. (Please refer to the code below). One way would be to define a map of Key to the required Value. Is there another approach to do this ?
import (
"fmt"
"reflect"
)
type Code int
const (
MY_CONST_KEY Code = 123
)
func main() {
x := "MY_CONST_KEY"
//Fetch Value of x as 123
}
Upvotes: 1
Views: 2209
Reputation: 42433
One way would be to define a map of Key to the required Value.
Yes, do that.
Is there another approach to do this ?
No.
Upvotes: -1
Reputation: 51
Instead of assigning x to a string, "MY_CONST_KEY", you can do x := MY_CONST_KEY
package main
import (
"fmt"
)
type Code int
const (
MY_CONST_KEY Code = 123
)
func main() {
x := MY_CONST_KEY
fmt.Println(x) // This fetch the value of x as 123
}
Upvotes: 0
Reputation: 1168
There is no way to do what you are asking. You cannot pass constants to the reflect package without instead passing their literal value.
As you correctly mentioned, you can use a map:
package main
import "fmt"
type Code int
var codes = map[string]Code{
"MY_CONST_KEY": 123,
"ANOTHER_CONST_KEY": 456,
}
func main() {
x := codes["MY_CONST_KEY"]
fmt.Println(x)
}
If you make sure the map is not exported (lower case c
in codes
), then it will only be available inside your package, so consumers of your package cannot modify the map at runtime.
Upvotes: 4