Home >Backend Development >Golang >How to Achieve Dynamic Type Return in Go?
Scenario:
In Golang Revel development, repetitive code arises due to similar data return types involving type struct. Consider the following functions:
func (c Helper) Brands() []*models.Brand { // Query rethinkdb and populate the Brand model var brands []*models.Brand rows.All(&brands) return brands } func (c Helper) BlogPosts() []*models.Post { // Query rethinkdb and populate the Post model var posts []*models.Post rows.All(&posts) return posts }
In both cases, the return type is the same (*[]struct). To avoid duplication, a dynamic return type approach is proposed:
func (c Helper) ReturnModels(modelName string) []*interface{} { // Query rethinkdb with modelName and return []*interface{} }
Questions:
Answer:
Yes, dynamic type return is achievable. The function should return interface{} rather than []*interface{}. Here's how it can be implemented:
func (c Helper) ReturnModels(modelName string) interface{} { // Query rethinkdb with modelName and return interface{} }
To utilize the returned value, type switches or type assertions are employed to cast it back to its original type:
Example:
if brands, ok := ReturnModels("brands").([]Brand); ok { // ... } if posts, ok := ReturnModels("posts").([]Post); ok { // ... }
By implementing this approach, code duplication can be significantly reduced by using a single helper function for data retrieval.
The above is the detailed content of How to Achieve Dynamic Type Return in Go?. For more information, please follow other related articles on the PHP Chinese website!