douzhao2047 2016-06-01 08:05
浏览 394
已采纳

在Golang中从数组中选择元素的最惯用方式?

I have an array of strings, and I'd like to exclude values that start in foo_ OR are longer than 7 characters.

I can loop through each element, run the if statement, and add it to a slice along the way. But I was curious if there was an idiomatic or more golang-like way of accomplishing that.

Just for example, the same thing might be done in Ruby as

my_array.select! { |val| val !~ /^foo_/ && val.length <= 7 }
  • 写回答

5条回答 默认 最新

  • douyao1856 2016-06-01 08:18
    关注

    There is no one-liner as you have it in Ruby, but with a helper function you can make it almost as short.

    Here's our helper function that loops over a slice, and selects and returns only the elements that meet a criteria captured by a function value:

    func filter(ss []string, test func(string) bool) (ret []string) {
        for _, s := range ss {
            if test(s) {
                ret = append(ret, s)
            }
        }
        return
    }
    

    Using this helper function your task:

    ss := []string{"foo_1", "asdf", "loooooooong", "nfoo_1", "foo_2"}
    
    mytest := func(s string) bool { return !strings.HasPrefix(s, "foo_") && len(s) <= 7 }
    s2 := filter(ss, mytest)
    
    fmt.Println(s2)
    

    Output (try it on the Go Playground):

    [asdf nfoo_1]
    

    Note:

    If it is expected that many elements will be selected, it might be profitable to allocate a "big" ret slice beforehand, and use simple assignment instead of the append(). And before returning, slice the ret to have a length equal to the number of selected elements.

    Note #2:

    In my example I chose a test() function which tells if an element is to be returned. So I had to invert your "exclusion" condition. Obviously you may write the helper function to expect a tester function which tells what to exclude (and not what to include).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题