Help
cancel
Showing results for 
Search instead for 
Did you mean: 
Highlighted
Tricat Lvl 2
Message 1 of 2

How to filter element(s) from a slice efficiently?

Golang has no built-in filter function like python. Is there any way to filter elements from a slice efficiently?

1 Reply
Tricat Lvl 3
Message 2 of 2

Re: How to filter element(s) from a slice efficiently?

Hi!

 

In Golang, I use the Robe Pike lib :

 

https://github.com/robpike/filter

 

package main

import (
    "fmt"
    "strings"
    "github.com/robpike/filter"
)

func isNoBarAndLessThanTenChar(a string) bool {
    return ! strings.HasPrefix(a, "bar_") && len(a) <= 19
}

func main() {
    a := []string{"foo_super", "bar_cool", "baz_awesome"}
    result := Choose(a, isNoBarAndLessThanFiveChar)
    fmt.Println(result) // [foo_super]
}

Else, you have an other idiomatic way here: https://stackoverflow.com/questions/37562873/most-idiomatic-way-to-select-elements-from-an-array-in-...