Home >Backend Development >Golang >Can Go Invoke a Struct Method Using Only Its String Name?
Struct Invocation by String
Question:
In Go, is it possible to invoke a method on a struct using a string representing the struct's name, without explicitly initializing an instance of the struct?
.NET Framework
In .NET Framework, we could use Reflection.Assembly.GetType() and MethodInfo to achieve this behavior. We could get the Type from the assembly using the string name of the type and then invoke the method on an instance of that type.
.NET Core
However, in .NET Core, Assembly.GetType() and MethodInfo are no longer available. The reflection API in .NET Core provides more controlled and type-safe access to metadata.
Go
In Go, the reflection package provides a way to inspect and manipulate types at runtime. The reflect.TypeOf function returns the type of a value, and the MethodByName function returns the method with the given name on the given type.
.Go Code Sample
package main import ( "fmt" "reflect" ) type MyStruct struct { } func (a *MyStruct) Hello() { fmt.Println("Hello from MyStruct!") } func main() { // Get the type of MyStruct. t := reflect.TypeOf(MyStruct{}) // Get the method with the name "Hello" on MyStruct. m := t.MethodByName("Hello") // Create a new instance of MyStruct. v := reflect.New(t) // Invoke the Hello method on the new instance. m.Call(v) // Output: Hello from MyStruct! }
.NET Code Sample
using System; using System.Reflection; public class Program { public static void Main(string[] args) { // Get the type of MyStruct using Reflection. Type t = Assembly.GetExecutingAssembly().GetType("MyStruct"); // Get the method with the name "Hello" on MyStruct. MethodInfo m = t.GetMethod("Hello"); // Create a new instance of MyStruct. object v = Activator.CreateInstance(t); // Invoke the Hello method on the new instance. m.Invoke(v, null); // Output: Hello from MyStruct! } public struct MyStruct { public void Hello() { Console.WriteLine("Hello from MyStruct!"); } } }
Summary
In Go, it is not possible to invoke a method on a struct using only a string representing the struct's name, as there is no pre-initialized registry of type names. Custom mapping or initialization is required to achieve this functionality.
The above is the detailed content of Can Go Invoke a Struct Method Using Only Its String Name?. For more information, please follow other related articles on the PHP Chinese website!