How to get the name of a variable as a string in Go?

Asked

Viewed 84 times

2

Is there any way to get the name of a variable in Go as string?

var progzila int

As I could get variable name above, it is possible?

  • Why do you need this? It is local or part of a structure?

  • It is local, I need to show its name on the console. In C# there is the operator nameof to get a variable name. There is something similar in Go?

2 answers

1


There is nothing like nameof of C#, including because this operator does not exist to do what you want, it is a way to avoid silly maintenance errors when changing the variable name. It would be nice to have GO, but in general languages do not care about these details.

The fact is that in local variables you don’t need it, it’s useful, but you don’t need it, you know the variable name. If you never change her name string by hand, if changing the name of the variable (rarely be necessary if it was well thought out and usually not change not cause much problem), just need to take more care and change also in the literal string, if the function is small the chance of making a mistake is very small. You always know the name of something you just used in the code. This goes for any language.

If you thought you needed to know the variable name in this way you were doing something wrong. This is usually true also for names of various structures. It is possible to get the variable name in this circumstance with reflection, but almost always the use of reflection is gambiarra, because the information is also there, you have it in hand, in some cases it may be useful because it is not so simple and changes can cause a little more maintenance, but you will change performance and robustness for less typing. There are other tools that give the smallest typing without compromising other points.

1

No way to get variable name (maybe with unsafe? but I don’t think so). However, it is possible to get the name of an element of a struct.

Whereas:

type MeuStruct struct {
    progzila int
}

Could use the val.Type().Field(i).Name of Reflect:

package main

import (
    "fmt"
    "reflect"
)

type MeuStruct struct {
    progzila int
}

func main() {
    ms := &MeuStruct{progzila: 42}

    val := reflect.ValueOf(ms).Elem()
    for i := 0; i < val.NumField(); i++ {
        fmt.Println(val.Type().Field(i).Name)
    }
}

Thus printing press:

progzila

Test here.


It is not the same thing, should not achieve the same goal, but it is what I believe is closest available.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.