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 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿