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 Like

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-golang

It depends.

For my cases I’m using '“reasign filtering”. Take a look

func ipv6Only(ips []net.IP) []net.IP {
    var ln int
    for _, ip := range ips {
        if ip.To4() != nil {
            continue // drop IPv4 address
        }
        ips[ln] = ip
        ln++
    }
    return ips[:ln]
}

https://play.golang.org/p/cvKkvqxdzih

This method keeps underlying array. And if you have a very big input slice and want ot reduce it to a small one and deallocate the original one, then this method is not for your. This method keeps original unerlying array to avoid unnecessay allocation of new one. It’s fast and good for memory and GC pressure in some cases.

2 Likes