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 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献