Home > Backend Development > Golang > Can Reflection Retrieve a Variable\'s Name from Its Value in Go?

Can Reflection Retrieve a Variable\'s Name from Its Value in Go?

Barbara Streisand
Release: 2024-11-26 11:45:11
Original
981 people have browsed it

Can Reflection Retrieve a Variable's Name from Its Value in Go?

Can I Retrieve a Variable's Name from Its Value?

Question: In the context of a templating system, how can I obtain a variable's name based solely on its value using reflection? This would allow me to replace placeholder values in a template with the actual variable names.

Using Reflection:

I attempted to use reflection to retrieve the variable name, but I was unsuccessful. Here's the code I tried:

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

var msg string
sa := []string{onevar, other}
for _, v := range sa {
    vName := reflect.TypeOf(v).Name()  // Attempt to get the variable name
    vName = fmt.Sprintf("{{%s}}", vName)  // Prefix the name with "{{" and "}}"
    msg = strings.Replace(msg, vName, v, -1)  // Replace the placeholder with the actual value
}
Copy after login

This approach doesn't yield the desired result because the slice sa only contains the variable values, not the variable names.

Answer:

Reflection cannot be used to retrieve the variable name in this scenario. The slice sa contains the values of the variables, not the variable names themselves. To achieve your goal of replacing placeholders with variable names, it is recommended to utilize a map instead of a slice. A map can associate variable names to their values, allowing for efficient and accurate replacement.

The above is the detailed content of Can Reflection Retrieve a Variable\'s Name from Its Value in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template