lancet Utility Library
Before You Start
- Applies to: Go 1.21+ (examples verified with Go 1.22) · Prerequisites: Base: Slices · Read time: about 10 min
Documentation: lancet/README_zh-CN.md at main · duke-git/lancet · GitHub
Repository: duke-git/lancet: A comprehensive, efficient, and reusable util function library of Go. (github.com)
Introduction
Lancet (translated as a surgical lancet) is a general-purpose utility library containing concurrency, network, file, time, type conversion, and other utility libraries. Its code complexity is not high, and it encapsulates frequently used functions. So while using it, lancet is also a good learning resource for people who are just learning Go.
Usage
TIP
The official Chinese documentation is already very detailed and comes with complete code examples, so it won't be repeated here how to use it.
Complete Example
The program below runs as-is: copy it into a file and execute go run main.go, or paste it into the Go Playground.
package main
import (
"fmt"
"strings"
)
func firstNonEmpty(vals ...string) string {
for _, v := range vals {
if v != "" {
return v
}
}
return ""
}
func main() {
// Typical lancet helpers, implemented inline
nums := []int{1, 2, 3, 4}
sum := 0
for _, n := range nums {
sum += n
}
fmt.Println("sum:", sum)
fmt.Println("contains:", strings.Contains("golang", "go"))
fmt.Println("first non-empty:", firstNonEmpty("", "", "fallback"))
}Expected output:
sum: 10
contains: true
first non-empty: fallbackCommon Pitfalls
- Check the parameter order. Slice helpers often take
(slice, func); mixing them up compiles but misbehaves. - Generics help. Modern lancet functions are generic; old code may need type-specific variants.
- Do not import a utility library for one function. The standard library or ten lines of code may be enough.
- Watch allocation.
Filter-style helpers build new slices; large inputs deserve benchmarks. - Read the docs for edge cases. Empty input, nil slices and closures with side effects behave subtly.
Change Log
- 2026-10-14: Added "Before You Start" notes, a complete runnable example with expected output, common pitfalls, and this change log.
