Home >Backend Development >Golang >Can Go Functions Dynamically Return Different Struct Types Using `interface{}`?
In your Revel application, you have encountered code redundancy caused by different functions returning similar data types. Instead of creating multiple helper functions for each model, you envision a dynamic solution that returns interface{} types. This question delves into the feasibility of this approach.
Yes, it is possible to dynamically return struct types in Go, but it requires careful consideration of interface{} and type assertion.
Instead of []*interface{}, you should declare your function to return interface{}. This allows the function to return any type, including structs.
func (c Helper) ReturnModels(modelName string) interface{}
Consider the following example:
type Post struct { Author string Content string } type Brand struct { Name string } var database map[string]interface{} // Simulates a dynamic data source func ReturnModels(modelName string) interface{} { return database[modelName] // Retrieve data from hypothetical database }
You can use type switches or type assertions to cast the return value back to its original type.
type switcher func(interface{}) interface{} var result switcher switch modelName := database["myModel"].(type) { case Brand: result = func(v interface{}) interface{} { return v.(Brand) } case Post: result = func(v interface{}) interface{} { return v.(Post) } } fmt.Println(result(database["myModel"]))
In this example, the switch statement evaluates the type of the data retrieved from the database. Based on the type, the result function is assigned to a specific casting function, which is then invoked.
Dynamically returning struct types in Go using interface{} is achievable but requires careful handling. Type assertions can be used to ensure the correct type is cast. Refer to the linked example and documentation for further guidance.
The above is the detailed content of Can Go Functions Dynamically Return Different Struct Types Using `interface{}`?. For more information, please follow other related articles on the PHP Chinese website!