In Go, creating a new instance of a type from a string is not a straightforward task. Go's static typing and dead code elimination mechanisms make it difficult to dynamically create objects based on type names stored as strings.
To address this limitation, one approach is to maintain a global map[string]reflect.Type. This map can be populated in the init() function of packages defining the discoverable types. By using this map, you can look up the reflect.Type of the desired type and employ reflect.New to obtain a pointer to a new object of that type.
type MyStruct struct { // ... } func init() { register("MyStruct", reflect.TypeOf(MyStruct{})) }
Once registered, you can create a new instance using reflection:
newObject := reflect.New(registered["MyStruct"]).Elem().Interface() myStruct := newObject.(MyStruct)
However, it's important to consider that reflection can introduce performance overhead and increase the complexity of your code. It may be more suitable to explore alternative approaches, such as:
The above is the detailed content of How Can I Instantiate a New Type in Go from a String?. For more information, please follow other related articles on the PHP Chinese website!