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


In Golang, I use the Robe Pike lib :

package main

import (

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:

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
    return ips[:ln]

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.