Enjoy A Slice of Pie! Dealing With Go Slices

Elliot Chance
Apr 4 · 2 min read
Photo by sheri silver on Unsplash

Everyone that has used Go has written some (perhaps many) slice utility methods like this:

func StringContains(ss []string, lookingFor string) bool {
    for _, s := range ss {
        if s == lookingFor {
            return true
        }
    }    return false
}

It’s one of those things that’s not so painful as to investigate a better solution, but just painful enough that it can be annoying sometimes.

There are several great packages out there for making this task easier; thoas/go-funk, leaanthony/slicer, viant/toolbox and alxrm/ugo to name a few. However, these use reflect to make the interface on the consumer as easy and flexible as possible. Which is great, but comes at the expense of performance and type safety.

So I’ve created github.com/elliotchance/pie that focuses on performance and type safety. It’s basically a collection of all those utility methods you would normally write, but has the same high performance and type safety you would otherwise expect.

In my experience when dealing with slices (excluding custom types) I really only operate with []string, []int and []float64. It’s also not unreasonable to update existing code to fit into these slice types. Unfortunately, if you are dealing with custom slice types pie will not be of any help.

It can be used with the Go-style package functions:

names := []string{"Bob", "Sally", "John", "Jane"}
shortNames := pie.StringsOnly(names, func(s string) bool {
   return len(s) <= 3
})// []string{"Bob"}

Or, they can be chained for more complex operations:

pie.Strings{"Bob", "Sally", "John", "Jane"}.
   Without(pie.Prefix("J")).
   Transform(strings.ToUpper).
   Last()// "SALLY"

There is a full list of all functions, conditionals and transforms in the README on the project page.

Originally published at http://elliot.land on April 4, 2019.

Elliot Chance

Written by

I’m a data nerd and TDD enthusiast from Sydney. I love exploring new technologies and working on modern ways to solve age old problems 🤓 elliotchance@gmail.com