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条)

报告相同问题?

悬赏问题

  • ¥50 gki vendor hook
  • ¥15 centos7中sudo命令无法使用
  • ¥15 灰狼算法和蚁群算法如何结合
  • ¥15 这是一个利用ESP32自带按键和LED控制的录像代码,编译过程出现问题,请解决并且指出错误,指导如何处理 ,协助完成代码并上传代码
  • ¥20 stm32f103,hal库 hal_usart_receive函数接收不到数据。
  • ¥20 求结果和代码,sas利用OPTEX程序和D-efficiency生成正交集
  • ¥50 adb连接不到手机是怎么回事?
  • ¥20 抓取数据时发生错误: get_mooncake_data() missing 1 required positional argument: 'driver'的问题,怎么改出正确的爬虫代码?
  • ¥15 vs2022无法联网
  • ¥15 TCP的客户端和服务器的互联