如何在Golang中返回动态类型struct?
发布时间:2020-12-16 19:29:28 所属栏目:大数据 来源:网络整理
导读:我在使用Golang Revel进行一些Web项目,到目前为止,我已经做了12个项目.在所有这些中,由于返回类型,我都有很多代码冗余.看这两个功能: func (c Helper) Brands() []*models.Brand{ //do some select on rethinkdb and populate correct model var brands []*
我在使用Golang Revel进行一些Web项目,到目前为止,我已经做了12个项目.在所有这些中,由于返回类型,我都有很多代码冗余.看这两个功能:
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 } 您可以看到它们都返回相同类型的数据(类型struct). func (c Helper) ReturnModels(modelName string) []*interface{} { //do rethinkdb select with modelName and return []*interface{} for modelName } 像这样,我可以只有一个帮助器返回数据类型,而不是 我的问题是: >这是可能的
是的,但是你的函数应该返回interface {}而不是[] *接口.
func (c Helper) ReturnModels(modelName string) interface{} {} 在这种情况下,您可以使用Type Switches and/or Type Assertions将返回值转换为原始类型. 例 注意:我从未使用过Revel,但以下代码片段应该给出一个一般的想法: Playground 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] } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |