Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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)
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...