3

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

1 Answers1

5

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
  • 389,944
  • 63
  • 907
  • 827
  • Thanks. This seems to be the only solution – Iwuchukwu Chijindu Jan 26 '21 at 10:22
  • To clarify: there's no Golang solution (other than workaround(s) named above) for this, like what [C++](https://stackoverflow.com/a/38696665/605356) and [Rust](https://stackoverflow.com/a/69921393/605356) apparently provide? Golang's [stringer tool](https://pkg.go.dev/golang.org/x/tools/cmd/stringer) looks interesting, but at first glance (to this newbie Golang developer) `stringer` may only be effective for constants. – Johnny Utahh Nov 22 '22 at 12:45
  • @JohnnyUtahh Go does not support this. The variable name is not passed. If you need it, you have to pass it explicitly (or use a workaround like a struct type). – icza Nov 22 '22 at 12:52
  • Thanks @icza ; an aside, a similar Q+A: https://stackoverflow.com/a/24845867/605356 – Johnny Utahh Nov 22 '22 at 12:53