Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Golang, can we declare some string value to variable name?

Tags:

variables

go

I have slices with some variable names

like

strList := ['abcd', 'efgh', 'ijkl']

and I want to make it to variables names(to make some object iterably) What I curious is that how can I make strings value to variable name. (in code) like strList[0] seems not allowed....

Thanks for your help!

like image 270
user3215204 Avatar asked Nov 30 '25 02:11

user3215204


1 Answers

Since your strings will be read at runtime and your variable names will be checked at compile time, it's probably not possible to actually create a variable with a name based on a string.

However, you can make a map that stores values with string keys. For example, if you wanted to hold integer values inside something you can look up using the values "abcd", "efgh", etc., you would declare:

myMap := map[string]int {
  "abcd": 1,
  "efgh": 2,
  "ijkl": 3,
}

and you could then read those values with e.g. myMap["abcd"] // 1.

like image 59
Jesse Amano Avatar answered Dec 02 '25 16:12

Jesse Amano