duanmu8911
duanmu8911
2017-11-15 04:44

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

  • iteration
已采纳

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 doutuo3899 4年前

    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)
    
    点赞 评论 复制链接分享