duanguanzai6181 2014-05-19 09:40
浏览 37
已采纳

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
        }
    }
  • 写回答

1条回答 默认 最新

  • douzhang1926 2014-05-19 10:56
    关注

    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/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用