[英]How to return dynamic type struct in Golang?
I am using Golang Revel for some web project and I did like 12 projects in that so far. 我正在使用Golang Revel进行一些网络项目,到目前为止我确实喜欢了12个项目。 In all of them I have a lot of code redundancy because of return types. 在所有这些中,由于返回类型,我有很多代码冗余。 Look at this two functions: 看看这两个功能:
func (c Helper) Brands() []*models.Brand{
//do some select on rethinkdb and populate correct model
var brands []*models.Brand
rows.All(&brands)
return brands
}
func (c Helper) BlogPosts() []*models.Post{
//do some select on rethinkdb and populate correct model
var posts []*models.Post
rows.All(&posts)
return posts
}
As you can see they they both returns same type of data (type struct). 正如您所看到的,它们都返回相同类型的数据(类型结构)。 My idea was just to pass string var like this: 我的想法就是像这样传递字符串var:
func (c Helper) ReturnModels(modelName string) []*interface{} {
//do rethinkdb select with modelName and return []*interface{} for modelName
}
Like this I can have just one helper for returning data types instead of doing same thing over and over again for different models but same data type. 像这样我可以只有一个帮助器来返回数据类型,而不是为不同的模型反复做同样的事情,但是相同的数据类型。
My questions are: 我的问题是:
Yes it's possible however your function should return interface{}
and not []*interface
. 是的,但是你的函数应该返回interface{}
而不是[]*interface
。
func (c Helper) ReturnModels(modelName string) interface{} {}
In this case you could use Type Switches and/or Type Assertions to cast the return value into it's original type. 在这种情况下,您可以使用Type Switches和/或Type Assertions将返回值强制转换为其原始类型。
Example 例
Note: I've never used Revel, but the following snippet should give you an a general idea: 注意:我从未使用过Revel,但以下代码段应该为您提供一个大致的想法:
package main
import "fmt"
type Post struct {
Author string
Content string
}
type Brand struct {
Name string
}
var database map[string]interface{}
func init() {
database = make(map[string]interface{})
brands := make([]Brand, 2)
brands[0] = Brand{Name: "Gucci"}
brands[1] = Brand{Name: "LV"}
database["brands"] = brands
posts := make([]Post, 1)
posts[0] = Post{Author: "J.K.R", Content: "Whatever"}
database["posts"] = posts
}
func main() {
fmt.Println("List of Brands: ")
if brands, ok := ReturnModels("brands").([]Brand); ok {
fmt.Printf("%v", brands)
}
fmt.Println("\nList of Posts: ")
if posts, ok := ReturnModels("posts").([]Post); ok {
fmt.Printf("%v", posts)
}
}
func ReturnModels(modelName string) interface{} {
return database[modelName]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.