Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GO: Best way to search element on structs

Tags:

go

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
        }
    }
like image 711
Mauricio Sartori Avatar asked Oct 21 '22 08:10

Mauricio Sartori


1 Answers

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/

like image 83
Dekker1 Avatar answered Oct 23 '22 00:10

Dekker1