如何优化下面的代码,搜索特定键值的地图数组(然后返回其他键值)?
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, ""
}
答案 0 :(得分:1)
你的代码是合理的,但它不是map的数组,它是struct的一部分。有效的方法是
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, ""
}
这不需要循环,并且具有O(1)复杂度。