douqiao5552 2015-05-13 07:38
浏览 74

GORM Golang如何优化此代码

I use GORM in my project and I want to create something like DB admin page.

To load records I send GET with params:

category: "name", // database table name

On server I have the next code:

func LoadItems(db *gorm.DB, category string) interface{} {
  var items interface{}

  loadItems := func(i interface{}) {
    err := db.Find(i).Error
    if err != nil {
      panic(err)
    }
    items = i
  }

  switch category {
  case "groups":
    var records []*models.Groups
    loadItems(&records)
  case "departments":
    var records []*models.Departments
    loadItems(&records)
  case .....
    ........
  }

  return items
}

Is it possible to replace switch because I have 10 tables and after record editing I send new data to server, where I re forced to use switch in other function to save it.

  • 写回答

1条回答 默认 最新

  • duanchouyi6730 2015-05-13 08:13
    关注

    I'm not familiar with gorm, but: Maybe store "department" (as key) and a variable of the corresponding model type in a map, and then referencing via key to the model. If not already, the models then have to implement a common interface in order to be able to store them in one map. Though, if that would be a better solution I'm not sure. Maybe a bit easier to maintain, because new model types only have to be added to the map, and you don't have to adjust switches on multiple places in your code.

    Another obvious way would be, outsourcing the switch to a function, returning a variable of a common interface type and using that on different places in your code. That would definitely not be faster, but easier to maintain.

    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c