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?

2
  • 1
    I don't think you can just get the identifier itself. But you can get part of the way using fmt.Printf("%+v\n", user) which gives you identifier and the value Jan 26, 2021 at 10:05
  • 1
    This works very well for struct but doesn't work for normal variables. Thanks Jan 26, 2021 at 10:20

1 Answer 1

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.

4
  • Thanks. This seems to be the only solution Jan 26, 2021 at 10:22
  • To clarify: there's no Golang solution (other than workaround(s) named above) for this, like what C++ and Rust apparently provide? Golang's stringer tool looks interesting, but at first glance (to this newbie Golang developer) stringer may only be effective for constants. Nov 22, 2022 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, 2022 at 12:52
  • Thanks @icza ; an aside, a similar Q+A: stackoverflow.com/a/24845867/605356 Nov 22, 2022 at 12:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.