如何获得源代码中的变量名(使用反射) [英] How to get the variable name as in the source code (using reflect)

查看:89
本文介绍了如何获得源代码中的变量名(使用反射)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个易于使用的模板系统.基本上,我只想创建一个具有不同变量(字符串)的切片,然后遍历该切片并将标记 {{}} 替换为实际值.因此,如果变量' name '是 onevar ,它将在模板中查找 {{onevar}} 并将其替换为的实际值变量.

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 .

问题:如何获取变量名?基本上,源代码中包含什么.是否可以 ?我已经尝试过使用反射功能,但是似乎无法正确处理.见下文g

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)
    }

推荐答案

您不能做这些事情.该分片不包含变量,但包含它们的,因此您无法获得它们的名称.只需使用地图即可.

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.

这篇关于如何获得源代码中的变量名(使用反射)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆