1

I have a value assigned to a variable. How do I print the name of the variable instead of the value assigned to the variable? I know I can hard code the variable name into the Printf function, but I don't want to use that. I want to use formater if something like that works in Go.

example

user := "Jada"
fmt.Println(user)

The above will print the value assigned to the variable, which is "Jada".

Is there a way I can have it print the variable name, user, instead of the variable value?

Flimzy
  • 68,325
  • 15
  • 126
  • 165

1 Answers1

3

When you pass a value to a function, the variable name is not passed to it, so it is impossible to print the name of the variable. It's not even possible to get the names of the parameters, for details, see Getting method parameter names.

The closest you can do is use a struct as the parameter type, and you can get and print the name of the fields (using reflection). Or use a map, and pass the variable name as the key.

icza
  • 342,548
  • 56
  • 784
  • 738