如何在Golang中返回动态类型struct?

如何在Golang中返回动态类型struct?,第1张

如何在Golang中返回动态类型struct?

是的,但是您的函数应该返回

interface{}
而不是应该返回
[]*interface

func (c Helper) ReturnModels(modelName string) interface{} {}

在这种情况下,您可以使用类型开关和/或类型断言将返回值转换为原始类型。

注意:我从未使用过Revel,但是以下代码片段应该为您提供一个总体思路:

*** 场

package mainimport "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]}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/zaji/4926293.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-12
下一篇2022-11-12

发表评论

登录后才能评论

评论列表(0条)

    保存