Go lancet
last modified October 30, 2026 Go 1.27
In this article we show how to work with the lancet utility library. Lancet
collects helpers that the standard library does not provide: string case
conversion, slice and map helpers, tuples, comparators, date arithmetics,
functional pipelines and small wrappers around os/exec and
net/http.
The examples in this article were compiled and run with Go 1.27.0 and lancet v2.4.0.
Installing lancet
Lancet is a normal Go module. The import path contains the major version, so
the module path ends in /v2.
$ go mod init example.com/lancet $ go get github.com/duke-git/lancet/v2@v2.4.0
The go get command records the dependency in go.mod.
Some subpackages import golang.org/x/exp and
golang.org/x/text, which are only added to go.sum
when go mod tidy runs with those imports present.
$ go mod tidy $ cat go.mod module example.com/lancet go 1.27.0 require github.com/duke-git/lancet/v2 v2.4.0
Without the tidy step, building a program that imports
slice fails with a missing go.sum entry message that
names the missing module. Running go mod tidy resolves it.
String helpers
The strutil package converts between naming conventions and offers
small predicates that are missing from strings.
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
msg := "an old falcon"
fmt.Println(strutil.CamelCase(msg))
fmt.Println(strutil.UpperCamelCase(msg))
fmt.Println(strutil.KebabCase(msg))
fmt.Println(strutil.SnakeCase(msg))
fmt.Println(strutil.Capitalize(msg))
fmt.Println(strutil.Reverse(msg))
fmt.Println(strutil.WordCount(msg))
fmt.Printf("%q\n", strutil.Ellipsis("the quick brown fox", 9))
fmt.Printf("%q\n", strutil.PadStart("7", 3, "0"))
fmt.Println(strutil.IsBlank(" \t"))
fmt.Println(strutil.IsBlank(" . "))
}
CamelCase keeps the first word lowercase and
UpperCamelCase capitalizes it. Reverse works on runes,
not bytes, so non-ASCII text survives. Ellipsis shortens the text
to the given length including the three dots, and IsBlank treats
whitespace as blank but punctuation as content.
$ go run main.go anOldFalcon AnOldFalcon an-old-falcon an_old_falcon An old falcon noclaf dlo na 3 "the quick..." "007" true false
Slice helpers
The slice package is generic: the element type is inferred from the
argument. Every predicate receives the index first and the element second, which
is the opposite of what slices.IndexFunc uses.
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/slice"
)
type User struct {
Name string
Age int
}
func main() {
vals := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
evens := slice.Filter(vals, func(i, v int) bool { return v%2 == 0 })
fmt.Println(evens)
doubled := slice.Map(vals, func(i, v int) int { return v * 2 })
fmt.Println(doubled)
fmt.Println(slice.Count(vals, 3))
fmt.Println(slice.CountBy(vals, func(i, v int) bool { return v > 7 }))
fmt.Println(slice.IndexOf(vals, 5))
users := []User{{"John", 30}, {"Roger", 25}, {"Lucy", 35}}
byAge := slice.GroupWith(users, func(u User) bool { return u.Age > 28 })
fmt.Println(byAge)
fmt.Println(slice.Join([]int{1, 2, 3}, ", "))
}
GroupWith returns a map whose keys are the values produced by the
function, so the boolean predicate splits the slice into two groups.
slice.Join is the generic counterpart of
strings.Join: it formats any slice, not only strings. The map is
printed with sorted keys, as fmt always does.
$ go run main.go
[2 4 6 8 10]
[2 4 6 8 10 12 14 16 18 20]
1
3
4
map[false:[{Roger 25}] true:[{John 30} {Lucy 35}]]
1, 2, 3
Tuples
Lancet tuples are generic structs with exported fields and an
Unbox method. Zip2 builds a slice of pairs from two
slices, and Unzip2 splits it back.
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/tuple"
)
func main() {
t2 := tuple.NewTuple2("falcon", 3)
name, n := t2.Unbox()
fmt.Println(name, n)
fmt.Printf("%+v\n", t2)
t3 := tuple.NewTuple3("sky", 2.5, true)
fmt.Printf("%+v\n", t3)
pairs := tuple.Zip2([]string{"a", "b"}, []int{1, 2})
fmt.Println(pairs)
keys, vals := tuple.Unzip2(pairs)
fmt.Println(keys, vals)
}
Unbox returns the fields in order, so it can be used directly in a
short variable declaration. The %+v verb prints the field names,
which makes the structure visible.
$ go run main.go
falcon 3
{FieldA:falcon FieldB:3}
{FieldA:sky FieldB:2.5 FieldC:true}
[{a 1} {b 2}]
[a b] [1 2]
Sorting with comparators
The algorithm package implements the classical sorting algorithms.
Each function sorts in place and takes a value that satisfies
constraints.Comparator, an interface with a single method
Compare(a, b any) int.
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/algorithm"
)
type User struct {
Name string
Age int
}
type byAge struct{}
func (c byAge) Compare(a, b any) int {
u1 := a.(User)
u2 := b.(User)
switch {
case u1.Age < u2.Age:
return -1
case u1.Age > u2.Age:
return 1
}
return 0
}
type intComparator struct{}
func (intComparator) Compare(a, b any) int {
x := a.(int)
y := b.(int)
switch {
case x < y:
return -1
case x > y:
return 1
}
return 0
}
func main() {
users := []User{
{"Peter", 20},
{"Julia", 14},
{"Lucia", 17},
{"Roman", 18},
{"Jan", 28},
}
algorithm.QuickSort(users, byAge{})
fmt.Println(users)
nums := []int{2, 1, 5, 3, 6, 4, -2, 0, 9, 11, -3}
algorithm.InsertionSort(nums, intComparator{})
fmt.Println(nums)
idx := algorithm.BinarySearch(nums, 6, 0, len(nums)-1, intComparator{})
fmt.Println(idx, nums[idx])
}
Because the interface method takes any, each comparator has to
assert the concrete type. BinarySearch expects an already sorted
slice together with the low and high indexes of the search range; it returned
the position of 6 in the sorted result.
$ go run main.go
[{Julia 14} {Lucia 17} {Roman 18} {Peter 20} {Jan 28}]
[-3 -2 0 1 2 3 4 5 6 9 11]
8 6
Comparator return values matter
The algorithms compare the result with == 1 and
== -1, so Compare must return exactly those values.
Returning the arithmetic difference, as cmp.Compare allows for
slices.SortFunc, silently produces an unsorted slice.
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/algorithm"
)
type diffComparator struct{}
func (diffComparator) Compare(a, b any) int {
return a.(int) - b.(int)
}
func main() {
nums := []int{2, 1, 5, 3, 6, 4, -2, 0, 9, 11, -3}
algorithm.InsertionSort(nums, diffComparator{})
fmt.Println(nums)
}
The program compiles and returns without an error, yet only the first pair was
swapped. The three-way comparison through switch shown in the
previous section is the safe form.
$ go run main.go [1 2 5 3 6 4 -2 0 9 11 -3]
Date and time helpers
The datetime package adds month, week and year boundaries and a
layout language that resembles the one used by Java and Python, with
yyyy for the year and mm for the month.
package main
import (
"fmt"
"time"
"github.com/duke-git/lancet/v2/datetime"
)
func main() {
t := time.Date(2026, time.October, 30, 15, 45, 35, 0, time.UTC)
fmt.Println(datetime.FormatTimeToStr(t, "yyyy-mm-dd"))
fmt.Println(datetime.FormatTimeToStr(t, "yyyy-mm-dd hh:mm:ss"))
fmt.Println(datetime.BeginOfMonth(t).Format(time.RFC3339))
fmt.Println(datetime.EndOfMonth(t).Format(time.RFC3339))
fmt.Println(datetime.BeginOfWeek(t, time.Monday).Format(time.RFC3339))
fmt.Println(datetime.EndOfWeek(t, time.Sunday).Format(time.RFC3339))
fmt.Println(datetime.AddMonth(t, 2).Format(time.RFC3339))
fmt.Println(datetime.DayOfYear(t))
fmt.Println(datetime.DaysBetween(t, t.AddDate(0, 0, 45)))
}
A fixed reference time is used so that the output does not change. The
BeginOfWeek and EndOfWeek functions take the weekday
that starts or ends the week; 30 October 2026 is a Friday, so the week begins on
Monday the 26th and ends on Sunday 1 November.
$ go run main.go 2026-10-30 2026-10-30 15:45:35 2026-10-01T00:00:00Z 2026-10-31T23:59:59Z 2026-10-26T00:00:00Z 2026-11-01T23:59:59Z 2026-12-30T15:45:35Z 302 45
Function pipelines
The function package provides combinators for single-argument
functions. Pipeline applies them from left to right, while
Compose applies them from right to left and requires all functions
to share the same variadic signature.
package main
import (
"fmt"
"strings"
"github.com/duke-git/lancet/v2/function"
)
func double(n int) int { return n * 2 }
func inc(n int) int { return n + 1 }
func main() {
p := function.Pipeline(double, inc)
fmt.Println(p(5))
compose := function.Compose(
func(s ...string) string { return strings.ToUpper(s[0]) },
func(s ...string) string { return strings.Join(s, "-") },
)
fmt.Println(compose("an", "old", "falcon"))
notBlank := function.Negate(func(s string) bool { return s == "" })
fmt.Println(notBlank("x"), notBlank(""))
both := function.And(
func(n int) bool { return n > 0 },
func(n int) bool { return n%2 == 0 },
)
fmt.Println(both(4), both(3))
}
Pipeline(double, inc) computes (5 * 2) + 1.
Compose applies the last function first, so the words are joined
and only then uppercased. Negate, And,
Or and their variants combine predicates.
$ go run main.go 11 AN-OLD-FALCON true false true false
Map helpers
The maputil package covers the lookups and filters that would
otherwise be written as a loop over a map. Keys are returned in map iteration
order, so they have to be sorted before printing.
package main
import (
"fmt"
"slices"
"github.com/duke-git/lancet/v2/maputil"
)
func main() {
stocks := map[string]int{"apples": 12, "oranges": 5, "pears": 0}
keys := maputil.Keys(stocks)
slices.Sort(keys)
fmt.Println(keys)
fmt.Println(maputil.GetOrDefault(stocks, "plums", -1))
fmt.Println(maputil.HasKey(stocks, "pears"))
inStock := maputil.Filter(stocks, func(k string, v int) bool { return v > 0 })
fmt.Println(inStock)
merged := maputil.Merge(stocks, map[string]int{"plums": 3})
fmt.Println(len(merged))
prices := map[string]float64{"apples": 1.2}
labels := maputil.MapValues(prices, func(k string, v float64) string {
return fmt.Sprintf("%s costs %.2f", k, v)
})
fmt.Println(labels)
}
GetOrDefault removes the two-value lookup, and
Merge returns a new map instead of modifying the arguments. The
printed maps are sorted by fmt, which makes the output stable.
$ go run main.go [apples oranges pears] -1 true map[apples:12 oranges:5] 4 map[apples:apples costs 1.20]
HTTP client helpers
The netutil package wraps net/http with a request
struct and a client that can decode JSON in one call. The test server below
keeps the example self-contained and reproducible.
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"github.com/duke-git/lancet/v2/netutil"
)
type Post struct {
ID int `json:"id"`
Title string `json:"title"`
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /posts/1", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(Post{ID: 1, Title: "an old falcon"})
})
mux.HandleFunc("GET /hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello %s", r.URL.Query().Get("name"))
})
srv := httptest.NewServer(mux)
defer srv.Close()
resp, err := netutil.HttpGet(srv.URL+"/hello", map[string]string{"name": "John"})
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
req := &netutil.HttpRequest{
RawURL: srv.URL + "/posts/1",
Method: http.MethodGet,
}
client := netutil.NewHttpClient()
resp2, err := client.SendRequest(req)
if err != nil {
panic(err)
}
defer resp2.Body.Close()
var post Post
if err := client.DecodeResponse(resp2, &post); err != nil {
panic(err)
}
fmt.Printf("%+v\n", post)
u, err := netutil.BuildUrl("https", "example.com", "/api/v1/users",
map[string][]string{"page": {"2"}, "sort": {"name"}})
fmt.Println(u, err)
}
HttpGet accepts optional headers and query parameters as
map[string]string values, which is why the name can be passed
directly. SendRequest returns the raw response and
DecodeResponse reads the JSON body into the target.
BuildUrl assembles and escapes the query string.
$ go run main.go
200 OK
{ID:1 Title:an old falcon}
https://example.com/api/v1/users?page=2&sort=name <nil>
System helpers
The system package offers the OS checks and the command runner that
scripts usually need. Neither function needs a third-party dependency, but they
save a few lines and hide the exec boilerplate.
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/system"
)
func main() {
fmt.Println(system.GetOsEnv("HOME") != "")
fmt.Println(system.IsLinux(), system.IsWindows(), system.IsMac())
fmt.Println(system.GetOsBits())
stdout, stderr, err := system.ExecCommand("echo lancet")
fmt.Printf("%q %q %v\n", stdout, stderr, err)
_, _, err = system.ExecCommand("false")
fmt.Printf("%v\n", err)
}
ExecCommand captures both output streams and returns them as
strings. A failing command does not panic; the status is reported through the
error, here exit status 1 from the false utility.
$ go run main.go true true false false 64 "lancet\n" "" <nil> exit status 1
Working with ZIP archives
The fileutil package includes file predicates and archive helpers.
Zip packs a directory tree, and the standard
archive/zip reader can inspect the result.
package main
import (
"archive/zip"
"fmt"
"os"
"github.com/duke-git/lancet/v2/fileutil"
)
func main() {
if err := os.MkdirAll("out", 0o755); err != nil {
fmt.Println(err)
return
}
if err := fileutil.Zip("data", "out/bundle.zip"); err != nil {
fmt.Println("zip:", err)
return
}
r, err := zip.OpenReader("out/bundle.zip")
if err != nil {
fmt.Println("open:", err)
return
}
defer r.Close()
for _, f := range r.File {
fmt.Printf("%-12s %d\n", f.Name, f.UncompressedSize64)
}
size, err := fileutil.FileSize("data/a.txt")
fmt.Println(size, err)
fmt.Println(fileutil.IsZipFile("out/bundle.zip"))
fmt.Println(fileutil.ListFileNames("data"))
}
The program expects a data directory with an a.txt
file and a sub/b.txt file. Zip keeps the directory
structure and stores the paths relative to the parent of the packed directory.
ListFileNames is not recursive, so only the top-level entry is
listed.
$ go run main.go a.txt 7 sub/b.txt 4 7 <nil> true [a.txt] <nil>
What lancet does not replace
Most helpers have a standard-library equivalent that is worth knowing first. The table lists the pairs that appear most often in lancet examples.
| Lancet call | Standard library |
|---|---|
slice.Filter, slice.Map | a for loop; slices.Collect only turns an iterator into a slice |
slice.CountBy | a for loop; the standard library has no counting helper |
maputil.Keys | maps.Keys returns an iterator |
algorithm.Sort* | slices.Sort, slices.SortFunc |
datetime.BeginOfMonth | time.Date with zeroed components |
fileutil.Zip | archive/zip with manual file walking |
The library is most useful for code that is not performance critical and for prototypes, where the shorter form is easier to read than a hand-written loop.
Source
In this article we have used lancet v2.4.0 for string case conversion, slice and map helpers, tuples, comparator-based sorting, date arithmetics, function pipelines, HTTP requests, system calls and ZIP archives.
Author
List all Go tutorials.