Apparently Go actually can filter?

yujiri8 profile image Ryan Westlund ・2 min read

I've thought for a while that Go's type system prevented a generic map or filter from being implemented. Today I came across someone who linked this library with this code:

package main

import (


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

func main() {
    a := []string{"foo_super", "bar_cool", "baz_awesome"}
    result := filter.Choose(a, isNoBarAndLessThanTenChar)

(The above code was actually very broken, this is a corrected version)

So of course I was shocked to see this. I thought I'd been proven wrong. But then I realized this snippet was deceptive because it doesn't do what it looks like: not only does the filter.Choose function not get type checking (which I knew), but the result is actually still an interface{} after (which I previously thought would happen but thought this snippet proved me wrong) - the only reason it works in fmt.Println is because fmt.Println takes interface{}. If you change it to print result[0], you get a type error.

But then I found out the library actually does work, because you can convert it back to []string with just .([]string)!

This is surprising because according to several StackOverflow people and the official Github wiki, converting from a slice of a concrete type to a slice of interface requires a for loop, which made me assume the other direction did too. But it doesn't.

So maybe filter and map are actually usable and worthwhile in Go? If there's nothing I'm missing, this is going to substantially improve my opinion of Go.

(I know there are performance downsides. So what? Premature optimization is evil.)

Posted on by:

yujiri8 profile

Ryan Westlund


I'm a programmer, writer, and philosopher. My Github account is yujiri8; all my content besides code is at yujiri.xyz.


markdown guide

I found this library and ultimately decided to go with github.com/thoas/go-funk it has other utilities i found useful like indexOf and find.

How go doesn't have these features built-in is beyond me (so many other languages do). That being said, I heard we might see a native more idiomatic version of these features with the upcoming generics feature.


This shouldn't be used because it has outdated code plus it will not work with upcoming standards of Go. I believe they are working on filter and map as generics are getting implemented.