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