Golang : Get constant name from value
Problem :
How to find out the constant name associated with a value? For example, if the a constant value is fixed to an integer during compile time. How does one find out the associated constant name just by processing the integer value during run time ?
Solution :
Use switch
statement to return the constant name.
NOTE : Not really an efficient and scalable solution, but it should work for small set of data
package main
import (
"fmt"
)
type wordInt int16
const (
HELLO = wordInt(1)
WORLD = wordInt(2)
HOW = wordInt(3)
ARE = wordInt(4)
YOU = wordInt(5)
)
func (w wordInt) String() string {
switch w {
case 1:
return "HELLO"
case 2:
return "WORLD"
case 3:
return "HOW"
case 4:
return "ARE"
case 5:
return "YOU"
}
// else return
return "NOT Defined"
}
func main() {
fmt.Printf("The constant name associated with integer %d is %s \n", 1, wordInt(1).String())
// can do without String() as well
fmt.Printf("The constant name associated with integer %d is %s \n", 2, wordInt(2))
fmt.Printf("The constant name associated with integer %d is %s \n", 3, wordInt(3))
fmt.Printf("The constant name associated with integer %d is %s \n", 5, wordInt(5))
fmt.Printf("The constant name associated with integer %d is %s \n", 9, wordInt(9))
}
Output :
The constant name associated with integer 1 is HELLO
The constant name associated with integer 2 is WORLD
The constant name associated with integer 3 is HOW
The constant name associated with integer 5 is YOU
The constant name associated with integer 9 is NOT Defined
Reference :
See also : Golang : How to get struct field and value by name
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+18.3k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+5.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+6.7k Golang : How to execute code at certain day, hour and minute?
+6k Golang : Mapping Iban to Dunging alphabets
+4.6k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+14.9k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+7.2k Your page has meta tags in the body instead of the head
+8k Golang : Generate random Chinese, Japanese, Korean and other runes
+8.3k Golang : Changing a RGBA image number of channels with OpenCV
+5k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+15.7k Golang : Find file size(disk usage) with filepath.Walk
+9.3k Golang : Generate random integer or float number