How can I optimize the code below for searching an array of maps for a specific key-value (and then return the other key-values)?
type userMap struct {
JiraUsername string
CHProjectID int
CHID string
}
func main() {
var userMaps []userMap
userMaps = append(userMaps, userMap{
JiraUsername: "ted",
CHProjectID: 81,
CHID: "23jk3f32jl3323",
})
fmt.Println(GetUserInfo(userMaps, "ted"))
}
func GetUserInfo(userMaps []userMap, jiraUsername string) (CHProjectID int, CHID string) {
for _, u := range userMaps {
if u.JiraUsername == jiraUsername {
return u.CHProjectID, u.CHID
}
}
return 0, ""
}
Your code is reasonable, but it's not array of map, it's slice of struct. The efficient way would be
type userMap struct {
JiraUsername string
CHProjectID int
CHID string
}
type UsersMap map[string]userMap
func main() {
userMaps := make(UsersMap)
userMaps["ted"] = userMap{
JiraUsername: "ted",
CHProjectID: 81,
CHID: "23jk3f32jl3323",
}
fmt.Println(GetUserInfo(userMaps, "ted"))
}
func GetUserInfo(userMaps UsersMap, jiraUsername string) (CHProjectID int, CHID string) {
if u, ok := userMaps[jiraUsername]; ok {
return u.CHProjectID, u.CHID
}
return 0, ""
}
This doesn't require loop and has O(1) complexity.