英文:
GO: Best way to search element on structs
问题
我正在使用go结构体进行工作,现在我有一个结构体,其中包含更多的结构体,在这种情况下,我需要找出切片中Id的值。我只有最后一个结构体中元素的名称,
我现在的做法是读取名为Genes的切片的每个元素,直到找到我的字符串名称。
有更好的做法来找到我的字符串名称吗?
以下是我正在阅读的方式:
idToFind := "0"
for _, genreItem := range responseStruct.Genes {
if strings.ToLower(genreItem.Translations.Translation.Name) == strings.ToLower(myNameValue){
idToFind = genreItem.Id
break
}
}
英文:
I'm working with go structs, Now I have a struct that has more structs in it, in this case I need to find out the value of the Id in an slice. I only have the name of an element in the last structure,
The way that I'm do it now, is reading each element of a slice called Genes till find my string Name.
Are there a better practice to find my string Name?
type GenresResponse struct {
Count int `xml:"count,attr"`
PageIndex int `xml:"page_index,attr"`
PageSize int `xml:"page_size,attr"`
NumOfResults int `xml:"num_of_results,attr"`
TotalPages int `xml:"total_pages,attr"`
Genes []Gene `xml:"gene"`
}
type Gene struct {
Category string `xml:"category,attr"`
Id string `xml:"id,attr"`
Translations Translations `xml:"translations"`
}
type Translations struct{
Translation Translation `xml:"translation"`
}
type Translation struct{
Lang string `xml:"lang,attr"`
Name string `xml:"name"`
}
And this is the way that I'm reading it
idToFind := "0"
for _, genreItem := range responseStruct.Genes {
if strings.ToLower(genreItem.Translations.Translation.Name) == strings.ToLower(myNameValue){
idToFind = genreItem.Id
break
}
}
答案1
得分: 3
你的代码似乎工作正常,据我所知,没有任何“更好”的方法来进行线性搜索。
但是,如果你处理大量的数据(尤其是在处理大量搜索时),你可能希望使用一种排序的方案(在这种情况下按名称排序基因数组)。在这种情况下,可以应用各种更快的搜索算法(如二分搜索),这将将搜索的复杂度从O(x)降低到O(log(x))。当搜索大量数据时,这可能会产生很大的差异。
关于二分搜索算法的更多信息可以在维基百科上找到:http://en.wikipedia.org/wiki/Binary_search_algorithm
Go语言还包含一个默认的包,可以处理排序和二分搜索,特别是其中的示例可能非常有用:http://golang.org/pkg/sort/
英文:
Your code seems to be working fine and to my knowledge there isn't any "better" way to do a linear search.
But if you're dealing with a lot of data (especially when dealing with a high amount of searching), you might want to use a scheme were the Gene array is sorted (by name in this case). In this case various faster searching algorithms (like binary search) can be applied, which lowers the complexity of searching from O(x) to O(log(x)). This can make a big difference when searching big amounts of data.
More on the binary search algorithm can be found on Wikipedia: http://en.wikipedia.org/wiki/Binary_search_algorithm
Go also includes a default package which can handle sorting and binary search, especially the examples could be quite useful: http://golang.org/pkg/sort/
答案2
得分: -1
Go与JSON很搭配。当然,从内存和CPU的角度来看,它并不是最优的选择。但是,你可以应用编组(marshaling)并搜索整个结构的文本...
英文:
Go works well with json. As an option, of course, it is not optimal from the point of view of memory and CPU. But, you can apply marshaling and search through the text of the entire structure...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论