3

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
        }
    }
Mauricio Sartori
  • 2,533
  • 6
  • 26
  • 28

2 Answers2

3

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/

Dekker1
  • 5,565
  • 25
  • 33
-1

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...