[英]Iterate over struct and perform database queries
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. 因此,我是新手,并且来自javascript / node背景,为了进行练习,我一直在重写自己的部分JavaScript代码。
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. 然后,在我处理返回绑定到此结构的JSON的api请求的函数中,我为处于活动状态的每个角色使用了for range循环。 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. 这种方法可以使用,但感觉并不完全正确,我很乐意从有经验的人那里得到一些建议。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.