为了账号安全,请及时绑定邮箱和手机立即绑定

如何制作接受字符串参数的函数,并根据它返回不同的结构类型?

如何制作接受字符串参数的函数,并根据它返回不同的结构类型?

Go
慕慕森 2023-06-05 13:27:13
我想创建一个接受字符串参数的函数,并根据字符串返回不同的类型在我当前的项目中,我使用 Go 版本 1.11.4 作为 Rest API,使用 PostgreSQL 11 来存储数据。该函数是为了避免代码冗余,我只需要一个函数来处理请求,没有这个函数我会写更多的请求处理程序。功能是:func GetArrayOfModelStructs(table_name string) interface{} {    if table_name == "prefs_n_cities" {        Prefs_n_cities_array := &models.Prefs_n_cities_array{}        return Prefs_n_cities_array    } else if table_name == "position_owner" {        Position_owners := &models.Position_owners{}        return Position_owners    } else if table_name == "region" {        Regions := &models.Regions{}        return Regions    } else if table_name == "district" {        Districts := &models.Districts{}        return Districts    } else if table_name == "locality" {        Localities := &models.Localities{}        return Localities    } else if table_name == "locality_type" {        Locality_types := &models.Locality_types{}        return Locality_types    } else if table_name == "population" {        Populations := &models.Populations{}        return Populations    }    return nil}func GetModelStructs(table_name string) interface{} {    if table_name == "prefs_n_cities" {        return models.Prefs_n_cities{}    } else if table_name == "position_owner" {        return models.Position_owner{}    } else if table_name == "region" {        return models.Regions{}    } else if table_name == "district" {        return models.District{}    } else if table_name == "locality" {        return models.Locality{}    } else if table_name == "locality_type" {        return models.Locality_type{}    } else if table_name == "population" {        return models.Population{}    }    return nil}我的结构示例如下:type Prefs_n_cities struct {    id          int32    Name        string    Description string    Region_id   int32}type Prefs_n_cities_array struct {    Array []Prefs_n_cities}
查看完整描述

1 回答

?
动漫人物

TA贡献1815条经验 获得超10个赞

你不能那样做。但是你有两个选择:

  1. interface{}像您一样返回一个,然后转换为具体类型。这可能会破坏您的目的。

  2. 将您的目的地作为指针传递,并就地修改它。所以像:

    func GetArrayOfModelStructs(table_name string, dst interface{}) error {

    然后让您的函数将值放入dst. 这确实要求传递的值dst是一个指针。这是一种非常常见的模式,可以在json.Unmarshal()sqlRows.Scan以及标准库和其他地方的许多其他地方看到。


查看完整回答
反对 回复 2023-06-05
  • 1 回答
  • 0 关注
  • 122 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信