GO: Best way to find an element in structs

I work with go structs. Now I have a structure in which there are more structures, in which case I need to find out the value of Id in the slice. I have only the name of the element in the last structure, Now when I do this, read each slice element called Genes until we find the Name line. Is there a better practice for finding 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 so I read it

idToFind := "0"
    for _, genreItem := range responseStruct.Genes {
        if strings.ToLower(genreItem.Translations.Translation.Name) == strings.ToLower(myNameValue){
            idToFind = genreItem.Id
            break
        }
    }
+4
source share
1 answer

Your code seems to be working fine, and as far as I know, there is no β€œbest” way to do a linear search.

( ), , Gene ( ). (, ), O (x) O (log (x)). .

: http://en.wikipedia.org/wiki/Binary_search_algorithm

Go , , : http://golang.org/pkg/sort/

+3

Source: https://habr.com/ru/post/1541090/


All Articles