A comprehensive, efficient, and reusable util function library of Go.
Last updated Jul 8, 2026
5.3k
Stars
519
Forks
8
Issues
0
Stars/day
Attention Score
86
Language breakdown
Go 100.0%
▸ Files
click to expand
README
Lancet is a comprehensive, efficient, and reusable util function library of go. Inspired by the java apache common package and lodash.js.
Website | 简体中文
Features
- 👏 Comprehensive, efficient and reusable.
- 💪 700+ go util functions, support string, slice, datetime, net, crypt...
- 💅 Only depends on two kinds of libraries: go standard library and golang.org/x.
- 🌍 Unit test for every exported function.
Installation
Note:
- For users who use go1.18 and above, it is recommended to install lancet v2.x.x. Cause in v2.x.x all functions were rewritten with generics of go1.18.
go get github.com/duke-git/lancet/v2 // will install latest version of v2.x.x
- For users who use version below go1.18, you should install v1.x.x. The latest of v1.x.x is v1.4.6.
go get github.com/duke-git/lancet // below go1.18, install latest version of v1.x.x
Usage
Lancet organizes the code into package structure, and you need to import the corresponding package name when use it. For example, if you use string-related functions,import the strutil package like below:
import "github.com/duke-git/lancet/v2/strutil"
Example
Here takes the string function Reverse (reverse order string) as an example, and the strutil package needs to be imported.
package main
import ( "fmt" "github.com/duke-git/lancet/v2/strutil" )
func main() { s := "hello" rs := strutil.Reverse(s) fmt.Println(rs) //olleh }
Documentation
Index
- Algorithm
- Compare
- Concurrency
- Condition
- Convertor
- Cryptor
- Datetime
- Datastructure
- EventBus
- Enum
- Fileutil
- Formatter
- Function
- Maputil
- Mathutil
- Netutil
- Pointer
- Random
- Retry
- Slice
- Stream
- Structs
- Strutil
- System
- Tuple
- Validator
- Xerror
1. Algorithm package implements some basic algorithm. eg. sort, search. index
import "github.com/duke-git/lancet/v2/algorithm"
Function list:
- BubbleSort : sorts slice with bubble sort algorithm, will change the original slice.
- CountSort : sorts slice with bubble sort algorithm, don't change original slice.
- HeapSort : sorts slice with heap sort algorithm, will change the original slice.
- InsertionSort : sorts slice with insertion sort algorithm, will change the original slice.
- MergeSort : sorts slice with merge sort algorithm, will change the original slice.
- QuickSort : sorts slice with quick sort algorithm, will change the original slice.
- SelectionSort : sorts slice with selection sort algorithm, will change the original slice.
- ShellSort : sorts slice with shell sort algorithm, will change the original slice.
- BinarySearch : returns the index of target within a sorted slice, use binary search (recursive call itself).
- BinaryIterativeSearch : returns the index of target within a sorted slice, use binary search (no recursive).
- LinearSearch : returns the index of target in slice base on equal function.
- LRUCache : implements memory cache with lru algorithm.
2. Compare package provides a lightweight comparison function on any type. index
import "github.com/duke-git/lancet/v2/compare"
Function list:
- Equal : Checks if two values are equal or not. (check both type and value)
- EqualValue : Checks if two values are equal or not. (check value only)
- LessThan : Checks if value
leftless than valueright.
- GreaterThan : Checks if value
leftgreater than valueright.
- LessOrEqual : Checks if value
leftless than or equal than valueright.
- GreaterOrEqual : Checks if value
leftless greater or equal than valueright.
- InDelta : Checks if two values are equal or not within a delta.
3. Concurrency package contain some functions to support concurrent programming. eg, goroutine, channel, async. index
import "github.com/duke-git/lancet/v2/concurrency"
Function list:
- NewChannel : create a Channel pointer instance.
- Bridge : link multiply channels into one channel.
- FanIn : merge multiple channels into one channel.
- Generate : creates a channel, then put values into the channel.
- Or : read one or more channels into one channel, will close when any readin channel is closed.
- OrDone : read a channel into another channel, will close until cancel context.
- Repeat : create channel, put values into the channel repeatedly until cancel the context.
- RepeatFn : create a channel, executes fn repeatedly, and put the result into the channel, until close context.
- Take : create a channel whose values are taken from another channel with limit number.
- Tee : split one chanel into two channels, until cancel the context.
- NewKeyedLocker : KeyedLocker is a simple implementation of a keyed locker that allows for non-blocking lock acquisition.
- Do :acquires a lock for the specified key and executes the provided function.
- NewRWKeyedLocker :RRWKeyedLocker is a read-write version of KeyedLocker.
- RLock : acquires a read lock for the specified key and executes the provided function.
- Lock : acquires a write lock for the specified key and executes the provided function.
- NewTryKeyedLocker : TryKeyedLocker is a non-blocking version of KeyedLocker.
- TryLock : TryLock tries to acquire a lock for the specified key.
- Unlock : Unlock releases the lock for the specified key.
4. Condition package contains some functions for conditional judgment. eg. And, Or, TernaryOperator... index
import "github.com/duke-git/lancet/v2/condition"
Function list:
- Bool : returns the truthy value of anything.
- And : returns true if both a and b are truthy.
- Or : returns false if neither a nor b is truthy.
- Xor : returns true if a or b but not both is truthy.
- Nor : returns true if neither a nor b is truthy.
- Xnor : returns true if both a and b or neither a nor b are truthy.
- Nand : returns false if both a and b are truthy.
- TernaryOperator : ternary operator.
5. Convertor package contains some functions for data conversion. index
import "github.com/duke-git/lancet/v2/convertor"
Function list:
- ColorHexToRGB : convert color hex to color rgb.
- ColorRGBToHex : convert rgb color to hex color.
- ToBool : convert string to bool.
- ToBytes : convert value to byte slice.
- ToChar : convert string to char slice.
- ToChannel : convert a collection of elements to a read-only channel.
- ToFloat : convert value to float64, if param is a invalid floatable, will return 0.0 and error.
- ToInt : convert value to int64 value, if input is not numerical, return 0 and error.
- ToJson : convert value to a json string.
- ToMap : convert a slice of structs to a map based on iteratee function.
- ToPointer : return a pointer of passed value.
- ToPointers : convert a slice of values to a slice of pointers.
- FromPointer : returns the value pointed to by the pointer.
- FromPointers : convert a slice of pointers to a slice of values.
- ToString : convert value to string.
- StructToMap : convert struct to map, only convert exported struct field.
- MapToSlice : convert map to slice based on iteratee function.
- EncodeByte : encode data to byte slice.
- DecodeByte : decode byte slice data to target object.
- DeepClone : creates a deep copy of passed item, can't clone unexported field of struct.
- CopyProperties : copies each field from the source struct into the destination struct.
- ToInterface : converts reflect value to its interface type.
- Utf8ToGbk : converts utf8 encoding data to GBK encoding data
- GbkToUtf8 : converts GBK encoding data to utf8 encoding data.
- ToStdBase64 : converts a value to a string encoded in standard Base64.
- ToUrlBase64 : converts a value to a string encoded in url Base64.
- ToRawStdBase64 : converts a value to a string encoded in raw standard Base64.
- ToRawUrlBase64 : converts a value to a string encoded in raw url Base64.
- ToBigInt : converts an integer of any supported type (int, int64, uint64, etc.) to \*big.Int.
6. Cryptor package is for data encryption and decryption. index
import "github.com/duke-git/lancet/v2/cryptor"
Function list:
- AesEcbEncrypt : encrypt byte slice data with key use AES ECB algorithm.
- AesEcbDecrypt : decrypt byte slice data with key use AES ECB algorithm.
- AesCbcEncrypt : encrypt byte slice data with key use AES CBC algorithm.
- AesCbcDecrypt : decrypt byte slice data with key use AES CBC algorithm.
- AesCtrCrypt : encrypt/ decrypt byte slice data with key use AES CRC algorithm.
- AesCfbEncrypt : encrypt byte slice data with key use AES CFB algorithm.
- AesCfbDecrypt : decrypt byte slice data with key use AES CFB algorithm.
- AesOfbEncrypt : encrypt byte slice data with key use AES OFB algorithm.
- AesOfbDecrypt : decrypt byte slice data with key use AES OFB algorithm.
- AesGcmEncrypt : encrypt byte slice data with key use AES GCM algorithm.
- AesGcmDecrypt : decrypt byte slice data with key use AES GCM algorithm.
- Base64StdEncode : encode string with base64 encoding.
- Base64StdDecode : decode string with base64 encoding.
- DesEcbEncrypt : encrypt byte slice data with key use DES ECB algorithm.
- DesEcbDecrypt : decrypt byte slice data with key use DES ECB algorithm.
- DesCbcEncrypt : encrypt byte slice data with key use DES CBC algorithm.
- DesCbcDecrypt : decrypt byte slice data with key use DES CBC algorithm.
- DesCtrCrypt : encrypt/decrypt byte slice data with key use DES CRY algorithm.
- DesCfbEncrypt : encrypt byte slice data with key use DES CFB algorithm.
- DesCfbDecrypt : decrypt byte slice data with key use DES CFB algorithm.
- DesOfbEncrypt : encrypt byte slice data with key use DES OFB algorithm.
- DesOfbDecrypt : decrypt byte slice data with key use DES OFB algorithm.
- HmacMd5 : return the md5 hmac hash of string.
- HmacMd5WithBase64 : return the md5 hmac hash of base64 string.
- HmacSha1 : return the hmac hash of string use sha1.
- HmacSha1WithBase64 : return the hmac hash of string use sha1 with base64.
- HmacSha256 : return the hmac hash of string use sha256.
- HmacSha256WithBase64 : return the hmac hash of string use sha256 with base64.
- HmacSha512 : return the hmac hash of string use sha512.
- HmacSha512WithBase64 : return the hmac hash of string use sha512 with base64.
- Md5Byte : return the md5 string of byte slice.
- Md5ByteWithBase64 : return the md5 string of byte slice with base64.
- Md5String : return the md5 value of string.
- Md5StringWithBase64 : return the md5 value of string with base64.
- Md5File : return the md5 value of file.
- Sha1 : return the sha1 value (SHA-1 hash algorithm) of base64 string.
- Sha1WithBase64 : return the sha1 value (SHA-1 hash algorithm) of string.
- Sha256 : return the sha256 value (SHA-256 hash algorithm) of string.
- Sha256WithBase64 : return the sha256 value (SHA256 hash algorithm) of base64 string.
- Sha512 : return the sha512 value (SHA-512 hash algorithm) of string.
- Sha512WithBase64 : return the sha512 value (SHA-512 hash algorithm) of base64 string.
- GenerateRsaKey : create rsa private and public pemo file.
- RsaEncrypt : encrypt data with ras algorithm.
- RsaDecrypt : decrypt data with ras algorithm.
- GenerateRsaKeyPair : creates rsa private and public key.
- RsaEncryptOAEP : encrypts the given data with RSA-OAEP.
- RsaDecryptOAEP : decrypts the data with RSA-OAEP
- RsaSign : signs the data with RSA.
- RsaVerifySign : verifies the signature of the data with RSA.
- GenerateSm2Key : generate SM2 private and public key.
- Sm2Encrypt : encrypt data with SM2 public key.
- Sm2Decrypt : decrypt data with SM2 private key.
- Sm3 : return the SM3 hash value (256-bit) of data.
- Sm4EcbEncrypt : encrypt data with SM4 ECB mode.
- Sm4EcbDecrypt : decrypt data with SM4 ECB mode.
- Sm4CbcEncrypt : encrypt data with SM4 CBC mode.
- Sm4CbcDecrypt : decrypt data with SM4 CBC mode.
7. Datetime package supports date and time format and compare. index
import "github.com/duke-git/lancet/v2/datetime"
Function list:
- AddDay : add or sub day to the time.
- AddHour : add or sub day to the time.
- AddMinute : add or sub day to the time.
- AddWeek : add or sub week to time.
- AddMonth : add or sub months to time.
- AddYear : add or sub year to the time.
- AddDaySafe : add or sub days to the time and ensure that the returned date does not exceed the valid date of the target year and month.
- AddMonthSafe : add or sub months to the time and ensure that the returned date does not exceed the valid date of the target year and month.
- AddYearSafe : Add or sub years to the time and ensure that the returned date does not exceed the valid date of the target year and month.
- BeginOfMinute : return the date time at the begin of minute of specific date.
- BeginOfHour : return the date time at the begin of hour of specific date.
- BeginOfDay : return the date time at the begin of day of specific date.
- BeginOfWeek : return the date time at the begin of week of specific date.
- BeginOfMonth : return the date time at the begin of month of specific date.
- BeginOfYear : return the date time at the begin of year of specific date.
- EndOfMinute : return the date time at the end of minute of specific date.
- EndOfHour : return the date time at the end of hour of specific date.
- EndOfDay : return the date time at the end of day of specific date.
- EndOfWeek : return the date time at the end of week of specific date.
- EndOfMonth : return the date time at the end of month of specific date.
- EndOfYear : return the date time at the end of year of specific date.
- GetNowDate : return format yyyy-mm-dd of current date.
- GetNowTime : return format hh-mm-ss of current time.
- GetNowDateTime : return format yyyy-mm-dd hh-mm-ss of current datetime.
- GetTodayStartTime : return the start time of today, format: yyyy-mm-dd 00:00:00.
- GetTodayEndTime : return the end time of today, format: yyyy-mm-dd 23:59:59.
- GetZeroHourTimestamp : return timestamp of zero hour (timestamp of 00:00).
- GetNightTimestamp : return timestamp of zero hour (timestamp of 23:59).
- FormatTimeToStr : convert time to string.
- FormatStrToTime : convert string to time.
- NewUnix : return unix timestamp of specific time.
- NewUnixNow : return unix timestamp of current time.
- NewFormat : return unix timestamp of specific time string, t should be "yyyy-mm-dd hh:mm:ss".
- NewISO8601 : return unix timestamp of specific iso8601 time string.
- ToUnix : return unix timestamp.
- ToFormat : return the time string 'yyyy-mm-dd hh:mm:ss' of unix time.
- ToFormatForTpl : return the time string which format is specific tpl.
- ToIso8601 : return iso8601 time string.
- IsLeapYear : check if param
yearis leap year or not.
- BetweenSeconds : returns the number of seconds between two times.
- DayOfYear : returns which day of the year the parameter date
tis.
- IsWeekend : checks if passed time is weekend or not.
- NowDateOrTime : returns current datetime with specific format and timezone.
- Timestamp : returns current second timestamp.
- TimestampMilli : returns current mill second timestamp.
- TimestampMicro : returns current micro second timestamp.
- TimestampNano : returns current nano second timestamp.
- TrackFuncTime : tracks function execution time.
- DaysBetween : returns the number of days between two times.
- GenerateDatetimesBetween : returns a slice of strings between two times.
- Min : returns the earliest time among the given times.
- Max : returns the latest time among the given times.
- MaxMin : returns the latest and earliest time among the given times.
8. Datastructure package contains some common data structure. eg. list, linklist, stack, queue, set, tree, graph. index
import list "github.com/duke-git/lancet/v2/datastructure/list"
import copyonwritelist "github.com/duke-git/lancet/v2/datastructure/copyonwritelist"
import link "github.com/duke-git/lancet/v2/datastructure/link"
import stack "github.com/duke-git/lancet/v2/datastructure/stack"
import queue "github.com/duke-git/lancet/v2/datastructure/queue"
import set "github.com/duke-git/lancet/v2/datastructure/set"
import tree "github.com/duke-git/lancet/v2/datastructure/tree"
import heap "github.com/duke-git/lancet/v2/datastructure/heap"
import hashmap "github.com/duke-git/lancet/v2/datastructure/hashmap"
import optional "github.com/duke-git/lancet/v2/datastructure/optional"
Structure list:
- List : a linear table, implemented with slice.
- CopyOnWriteList : a thread-safe list implementation that uses go slicing as its base.
- Link : link list structure, contains singly link and doubly link.
- Stack : stack structure(fifo), contains array stack and link stack.
- Queue : queue structure(filo), contains array queue, circular queue, link queue and priority queue.
- Set : a data container, like slice, but element of set is not duplicate.
- Tree : binary search tree structure.
- Heap : a binary max heap.
- Hashmap : hash map structure.
- Optional : Optional container.
9. EventBus is an event bus used for handling events within an application. Index
import "github.com/duke-git/lancet/v2/eventbus"
Function list:
- NewEventBus : Create an EventBus instance.
- Subscribe : subscribes to an event with a specific event topic and listener function.
- Unsubscribe : unsubscribes from an event with a specific event topic and listener function.
- Publish : publishes an event with a specific event topic and data payload.
- ClearListeners : clears all the listeners.
- ClearListenersByTopic : clears all the listeners by topic.
- GetListenersCount : returns the number of listeners for a specific event topic.
- GetAllListenersCount : returns the total number of all listeners.
- GetEvents : returns all the events topics.
- SetErrorHandler : sets the error handler function.
10. Package enum provides a simple enum implementation. Index
import "github.com/duke-git/lancet/v2/enum"
Function list:
- NewItem : Creates a new enum item.
- NewItemsFromPairs : Creates enum items from a slice of Pair structs.
- Value : Returns the value of the enum item.
- Name : Returns the name of the enum item.
- Valid : Checks if the enum item is valid. If a custom check function is provided, it will be used to validate the value.
- MarshalJSON : Implementation of json.Marshaler interface.
- NewRegistry : Creates a new enum registry.
- Add : Adds enum items to the registry.
- Remove : Removes an enum item from the registry by its value.
- Update : Updates the name of an enum item in the registry by its value.
- GetByValue : Retrieves an enum item by its value.
- GetByName : Retrieves an enum item by its name.
- Items : Returns a slice of all enum items in the registry.
- Contains : Checks if an enum item with the given value exists in the registry.
- Size : Returns the number of enum items in the registry.
- Range : Iterates over all enum items in the registry and applies the given function.
- SortedItems : Returns a slice of all enum items sorted by the given less function.
- Filter : Returns a slice of enum items that satisfy the given predicate function.
11. Fileutil package implements some basic functions for file operations. index
import "github.com/duke-git/lancet/v2/fileutil"
Function list:
- ClearFile : write empty string to target file.
- CreateFile : create file in path.
- CreateDir : create directory in absolute path.
- CopyFile : copy src file to dest file.
- CopyDir : copy src directory to dest directory.
- FileMode : return file's mode and permission.
- MiMeType : return file mime type.
- IsExist : checks if a file or directory exists.
🔗 More in this category