duanmu8911 2017-11-15 04:44
浏览 70
已采纳

遍历结构并执行数据库查询

So I'm new to go and I come from a javascript/node background and for practice, I've been rewriting some of my javascript code into go.

I have a situation where I have an struct (in node it was my object) and I need to iterate over it and perform two database queries. I have something that works but it seems costly and repetitive.

Struct:

type SiteUsers struct {
    Active struct {
        Moderators []string `json:"moderators"`
        Admins     []string `json:"admins"`
        Regulars   []string `json:"regulars"`
    } `json:"active"`
}

Then in the function where I handle an api request that returns JSON binded to this struct I use a for range loop for each role under active. For each one I perform the same first query and then a second one that is specific to each one.

v := getSiteUsers(&usrs, website)

for _, moderators := range v.Active.Moderators {
    // Insert into user table
    // Insert into user table with role of moderator
}

for _, admins := range v.Active.Admins {
    // Insert into user table
    // Insert into user table with role of admin
}

for _, regulars := range v.Active.Regulars {
    // Insert into user table
    // Insert into user table with role of regular
}

This method will work but it doesn't feel completely right and I would love to get some input from people experienced with go.

  • 写回答

1条回答 默认 最新

  • doutuo3899 2017-11-15 18:36
    关注

    Would something like this be better?

    v := getSiteUsers(&usrs, website)
    
    insertUsers := func(users []string, role roleType) {
        for _, user := range users {
            // Insert into user table
            // Insert into user table with given role
        }
    }
    
    insertUsers(v.Active.Moderators, moderatorRole)
    insertUsers(v.Active.Admins, adminRole)
    insertUsers(v.Active.Regulars, regularRole)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法