Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the variable name as in the source code (using reflect)

Tags:

go

I'm trying to build an easy to use templating system. Basically I just want to create a slice with different variables ( strings ) and then loop through the slice and replace the markup {{}} with the actual values. So if the variable 'name' is onevar it will look in the template for {{onevar}} and replace that with the actual value of the variable .

Question: how do I get the variable name? Basically what's in the source code. Is it possible ? I've tried something with reflect but seems I couldn't get it right. See belowg

onevar := "something"
other := "something else"

var msg string
    sa := []string{onevar, other}
    for _, v := range sa {
        vName := reflect.TypeOf(v).Name()
        vName = fmt.Sprintf("{{%s}}", vName)
        msg = strings.Replace(msg, vName, v, -1)
    }
like image 230
hey Avatar asked Jul 19 '14 04:07

hey


People also ask

How do you print a variable name instead of a value?

To print a variable's name: Split the string on the equal sign and get the variable's name. Use the print() function to print the variable's name.

How do you get the value of a variable in Python?

You can refer to the name of a variable to access its value. The value of a variable can be changed throughout your program. Variables are declared using this syntax: name = value. Python variables are useful because they allow you to reduce the need to repeat the same value in your code.


1 Answers

You cannot do such stuff. The slice does not contain the variables but their values, so you cannot get their name. Just use a map.

like image 120
Volker Avatar answered Sep 29 '22 15:09

Volker