Reflection: Struct by String
The question arises: is it possible to invoke a struct's method by specifying its name as a string via reflection?
In Go, reflection relies on a value to determine the underlying type. Using a string as an expression to obtain the type, as attempted in the code snippet provided, is not possible.
The accepted answer in a similar question suggests matching the string name against the target type. However, this approach requires manual type mapping and does not provide a direct solution for accessing a struct by its name as a string.
Conclusion
Unfortunately, there is no built-in mechanism or registry in Go that allows the direct invocation of a struct's method using only its name as a string. To achieve this, a custom type registry would need to be implemented, which would require manual mapping of type names to values.
The above is the detailed content of Can Go Reflection Invoke a Struct Method Using a String Name?. For more information, please follow other related articles on the PHP Chinese website!