tools

package
v2.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 29, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var TimePrecisionChinese = map[TimePrecision]string{
	PrecisionYear:   "年",
	PrecisionMonth:  "月",
	PrecisionWeek:   "周",
	PrecisionDay:    "日",
	PrecisionHour:   "小时",
	PrecisionMinute: "分钟",
	PrecisionSecond: "秒",
}

Functions

func AdjustTimezoneIfNeeded

func AdjustTimezoneIfNeeded(t time.Time) time.Time

AdjustTimezoneIfNeeded 检查时区,如果不是东八区则调整时区但保持时间值不变

func Any2Byte

func Any2Byte(src any) []byte

Any2Byte 将任意类型转换为字节数组

func Any2Int

func Any2Int[T constraints.Integer](_v any) (T, error)

func Any2Map

func Any2Map(src any) (any, error)

func Any2Reader

func Any2Reader(src any) *bytes.Reader

Any2Reader 将任意类型转换为 io.Reader

func Any2bool

func Any2bool(_v any) (bool, error)

Any2bool 尝试将任意类型转换为 bool

func Any2bytes

func Any2bytes(v any) ([]byte, error)

Any2bytes 尝试将任意类型转换为 []byte

func Any2float64

func Any2float64(_v any) (float64, error)

Any2float64 尝试将任意类型转换为 float64

func Any2int

func Any2int(_v any) (int64, error)

Any2int 尝试将任意类型转换为 int Deprecated: 请使用 Any2Int

func Any2string

func Any2string(v any) string

Any2string 将任意类型转换为字符串

func AnySlice2Str

func AnySlice2Str(slice []any, _sep ...string) string

AnySlice2Str 将任意切片转成字符串

func AnySlice2StrSlice

func AnySlice2StrSlice(slice []any) []string

func AnySlice2StrWithEmpty

func AnySlice2StrWithEmpty(slice []any, _sep ...string) string

func ArrayChunk

func ArrayChunk[T any](slice []T, size int) [][]T

ArrayChunk 高性能泛型切片分块函数

func ArrayChunkCopy

func ArrayChunkCopy[T any](slice []T, size int) [][]T

ArrayChunkCopy 高性能且安全的版本,会复制数据而不是引用原切片

func AutoDetectTimestampString

func AutoDetectTimestampString(timestampStr string) (time.Time, error)

AutoDetectTimestampString 解析字符串形式的时间戳并转换为 time.Time 对象 timestampStr 是时间戳字符串 这个函数在最近一百年内还是挺好使的哈,过了2286-11-21 01:46:39 就不管用了

func AutoRetry

func AutoRetry(retryCount int, retryInterval time.Duration, f func() bool) bool

func AutoRetryWithErr

func AutoRetryWithErr(retryCount int, retryInterval time.Duration, f RetryCallbackFunc) error

func AutoTimeDuration

func AutoTimeDuration(input time.Duration, unit time.Duration, dValue ...time.Duration) time.Duration

AutoTimeDuration 自动转换时间单位,主要是用于 ini json yaml 几种配置文件 解析出来的时间单位不一致。

func AvgFloat32

func AvgFloat32(d1, d2 float32, isf bool) float32

func AvgInt32

func AvgInt32(d1, d2 int32, isf bool) int32

AvgInt32 计算平均数

func AvgInt64

func AvgInt64(d1, d2 int64, isf bool) int64

func AvgSlice

func AvgSlice[T Number](slice []T) T

AvgSlice 返回原类型的平均数(浮点结果)

func AvgUint64

func AvgUint64(d1, d2 uint64, isf bool) uint64

func Bool1time

func Bool1time(b bool) int

func Booltostring

func Booltostring(b bool) string

Booltostring 布尔转 1 0

func ByteFormat

func ByteFormat(s int) string

ByteFormat 字节格式化

func BytesToInt

func BytesToInt(b []byte) int

BytesToInt 字节转换成整形

func BytesToUint16

func BytesToUint16(b []byte) uint16

func CamelString

func CamelString(s string) string

CamelString 蛇形转驼峰

func CheckIsObject

func CheckIsObject(v any) bool

CheckIsObject 检查给定的值是否是一个对象(map、slice、struct、指针)

func CompareArray

func CompareArray[T comparable](a, b []T) bool

func CompareArraySorted

func CompareArraySorted[T Ordered](a, b []T) bool

CompareArraySorted 比较两个数组在排序后是否相同(适用于可排序类型)

func Contains

func Contains[T comparable](slice []T, target T, filters ...func(T) T) bool

Contains 检查某个值是否在切片中(泛型实现)

func ContainsAny

func ContainsAny[T comparable](elems []T, targets []T) bool

ContainsAny 检查 `elems` 中是否有任意一个元素在 `targets` 里

func ContainsAnyHashBest

func ContainsAnyHashBest[T any, H comparable](elems []T, targets []T, hashFunc func(T) H, equal func(a, b T) bool) bool

ContainsAnyHashBest 检查 `elems` 中是否有任意一个元素在 `targets` 里,自定义比较函数 elems 检查列表 targets 被搜索列表 hashFunc 计算hash equal 精确比较

func ContainsByField

func ContainsByField[T any, F comparable](slice []T, target F, fieldExtractor func(T) F) bool

ContainsByField 可用于[]struct中,检查某个字段的值是否存在

func ContainsDotDot

func ContainsDotDot(v string) bool

func ContainsFilterHelper

func ContainsFilterHelper[T any](v T, filters ...func(T) T) T

func ContainsFunc

func ContainsFunc[T any](slice []T, target T, equal func(a, b T) bool) bool

ContainsFunc 支持自定义比较逻辑(适用于不可比较类型,如 `struct` 带非 `comparable` 字段)

func ConvertTimeFormat

func ConvertTimeFormat(format string, lang string) string

ConvertTimeFormat 多语言时间格式转换器

func CreateSignature

func CreateSignature(s, key string) string

CreateSignature 带有 密钥的 sha1 hash

func CutStrSlice2Slice

func CutStrSlice2Slice(s []string, key string, direct int) []string

CutStrSlice2Slice 获取切片的子切片

func DeleteStrarr

func DeleteStrarr(arr []string, val string) []string

DeleteStrarr 删除字符串切片的某一个元素 noinspection all

func DiffRangeable

func DiffRangeable[Idx comparable, V any, C comparable](src, dst Rangeable[Idx, V, C]) (inSrc []V, common [][2]V, inDst []V)

DiffRangeable 比较两个Rangeable 返回两个Rangeable的差异 src: 源数据 dst: 目标数据 返回值: inSrc: 目标数据中不存在的元素 common: 两个Rangeable中都存在的元素,[2]V 第一个是src中的,第二个是dst中的 inDst: 源数据中不存在的元素 noinspection all

func EmptyString2

func EmptyString2(s string) string

EmptyString2 空字符串转为 -

func FileAbsWithCurrent

func FileAbsWithCurrent(current, cpath string) string

FileAbsWithCurrent 生成文件的绝对路径,根目录手动指定

func FileAppendContents

func FileAppendContents(path, content string) error

FileAppendContents 快速简易写文件(追加)

func FileGetContents

func FileGetContents(path string) ([]byte, error)

FileGetContents 快速简易读取文件

func FilePutContents

func FilePutContents(path, content string) error

FilePutContents 快速简易写文件

func FilePutContentsbytes

func FilePutContentsbytes(path string, content []byte) error

func FilePutWithReader

func FilePutWithReader(path string, rd io.Reader) error

func Fileabs

func Fileabs(cpath string) string

Fileabs 生成文件的绝对路径 noinspection SpellCheckingInspection

func Float32tostring

func Float32tostring(f float32) string

Float32tostring 将 float32 转换为字符串 noinspection all

func Float64tostring

func Float64tostring(f float64) string

Float64tostring 将 float64 转换为字符串 noinspection all

func FormatWeek

func FormatWeek(t time.Time) string

FormatWeek 将时间格式化为202501(年+周数)格式

func GetDurationFromPrecision

func GetDurationFromPrecision(precision TimePrecision) time.Duration

GetDurationFromPrecision 根据时间精度返回对应的时间段

func GetFormatFromPrecision

func GetFormatFromPrecision(precision TimePrecision) string

GetFormatFromPrecision 根据时间精度获取标准的时间格式字符串

func GetIpVersion

func GetIpVersion(ip string) (string, error)

GetIpVersion 解析ip地址,确认ip版本

func GetKeysWithPrefix

func GetKeysWithPrefix[T any](m map[string]T, prefix string) []string

GetKeysWithPrefix 返回 map 中所有以给定前缀开头的 keys

func GetLevel2MapValue

func GetLevel2MapValue[K any](inp map[string]map[string]K, key1, key2 string) (K, bool)

GetLevel2MapValue 获取二级map的值

func GetNextPeriodStart

func GetNextPeriodStart(t time.Time, format string) time.Time

GetNextPeriodStart 根据时间格式模板获取下一个周期的起始时间

func GetNextPeriodTime

func GetNextPeriodTime(t time.Time, format string) time.Time

GetNextPeriodTime 获取下一个周期的当前时间点(保持相同时间位置)

func GetNextPeriodTimeByPrecision

func GetNextPeriodTimeByPrecision(t time.Time, precision TimePrecision) time.Time

func HasKeyWithPrefix

func HasKeyWithPrefix[T any](m map[string]T, prefix string) bool

HasKeyWithPrefix 检查 map 中是否存在以给定前缀开头的 key

func Int32tobooltoint

func Int32tobooltoint(i int32) int

Int32tobooltoint 将 int32 转换为 bool 并返回 int noinspection all

func IsArray

func IsArray(v any) bool

IsArray 检查值是否为数组或切片

func IsPowerOfTwo

func IsPowerOfTwo[T constraints.Integer](n T) bool

IsPowerOfTwo 位运算 - 最简洁高效 检测输入数字是否是2的幂

func IsStruct

func IsStruct(ipt any) (name string, isStruct bool, isAnonymous bool, dst reflect.Type)

func IsZero

func IsZero[T comparable](v T) bool

IsZero isZero 检查值是否为类型的零值

func JsonEncode

func JsonEncode(j any) ([]byte, error)

func Map2SliceWithHeader

func Map2SliceWithHeader(m map[string]any, header []string) []any

func Map2Struct

func Map2Struct(dst any, src map[string]any, customConvert map[string]func(dst any, src map[string]any) error) error

Map2Struct 将map转换为结构体 dst 需要传入一个变量的指针

func MapDeepCopy

func MapDeepCopy[T any](src T, dst *T)

MapDeepCopy map 深拷贝

func MapKeys

func MapKeys[K comparable, V any](m map[K]V) []K

func Max

func Max[T cmp.Ordered](d1, d2 T) T

func MaxFloat32

func MaxFloat32(d1, d2 float32) float32

func MaxInt32

func MaxInt32(d1, d2 int32) int32

func MaxInt64

func MaxInt64(d1, d2 int64) int64

func MaxUint64

func MaxUint64(d1, d2 uint64) uint64

func Min

func Min[T cmp.Ordered](d1, d2 T) T

func MinFloat32

func MinFloat32(d1, d2 float32) float32

func MinInt32

func MinInt32(d1, d2 int32) int32

func MinInt64

func MinInt64(d1, d2 int64) int64

func MinMaxAvgSum

func MinMaxAvgSum(nums []int) (min int, max int, avg float64, sum int)

MinMaxAvgSum 获取数组中最大值最小值平均值和求和

func MinUint64

func MinUint64(d1, d2 uint64) uint64

func Mkdir

func Mkdir(path string) error

Mkdir 判断目录是否存在,否则创建目录

func MustAny2Int

func MustAny2Int[T constraints.Integer](_v any) T

func MustAny2float64

func MustAny2float64(_v any) float64

func MustAny2int

func MustAny2int(_v any) int64

func MustReadReader

func MustReadReader(r io.Reader) []byte

func MustStringReader

func MustStringReader(r io.Reader) string

func NestedMapSet

func NestedMapSet[K comparable, V comparable, T any](m map[K]map[V]T, outerKey K, innerKey V, value T)

NestedMapSet 自动初始化嵌套 map 并设置值 如果内层map不存在,会自动创建

func NumberEmptyString

func NumberEmptyString(s string) string

func Object2MapStringAny

func Object2MapStringAny(input any) (map[string]any, bool)

func PadRight

func PadRight(str string, padStr string, lenght int) string

PadRight 在字符串后面补齐固定字符,并达到n个长度

func ProbabilityTrigger

func ProbabilityTrigger(probability float64) bool

ProbabilityTrigger 使用线程安全的随机数生成器根据给定的概率触发事件

func RandomString

func RandomString(n int, allowedChars ...[]rune) string

RandomString 伪随机字符串

func ReadRowWithFile

func ReadRowWithFile(file io.Reader, callback ReadRowCallback) error

func RemoveAll

func RemoveAll(path string)

func RemoveDuplicates

func RemoveDuplicates[T comparable](slice []T) []T

RemoveDuplicates 对slice去重

func RemoveDuplicatesWithKeyFunc

func RemoveDuplicatesWithKeyFunc[T any, K comparable](slice []T, keyFunc func(T) K) []T

RemoveDuplicatesWithKeyFunc 对slice去重,使用keyFunc生成比较键

func RetryRunner

func RetryRunner(retry int, sleep time.Duration, callback RetryCallbackFunc)

RetryRunner 重试执行函数

func ReverseMapUnique

func ReverseMapUnique[K comparable, V comparable](m map[K]V) map[V]K

ReverseMapUnique 反转值唯一的 map

func RunAsyncFunc

func RunAsyncFunc(enable bool, f func())

RunAsyncFunc 异步运行

func RunAsyncTickerFunc

func RunAsyncTickerFunc(ctx context.Context, enable bool, d time.Duration, f func(), runFirst ...bool)

RunAsyncTickerFunc 异步运行,并定时执行 ctx 用于控制循环的退出 enable 是否启用 d 执行间隔 f 要执行的函数 runFirst 是否先执行一次

func RunAsyncTickerProbabilityFunc

func RunAsyncTickerProbabilityFunc(ctx context.Context, enable bool, d time.Duration, probability float64, f func())

RunAsyncTickerProbabilityFunc 异步运行,并定时执行,概率触发

func RunAsyncTickerProbabilityWithContext

func RunAsyncTickerProbabilityWithContext(ctx context.Context, enable bool, d time.Duration, probability float64, f func(ctx context.Context))

func RunAsyncTickerWithContext

func RunAsyncTickerWithContext(ctx context.Context, enable bool, d time.Duration, f func(ctx context.Context))

func RunOnContextDone

func RunOnContextDone(ctx context.Context, callback func())

RunOnContextDone 在context.Done()时执行回调函数

func RunSyncFunc

func RunSyncFunc(enable bool, f func())

RunSyncFunc 同步运行

func SearchInt64Slice deprecated

func SearchInt64Slice(s int64, arr []int64) bool

Deprecated: 使用 Contains

func SearchIntSlice deprecated

func SearchIntSlice(s int, arr []int) bool

SearchIntSlice 在整数切片中搜索指定的元素,并返回是否找到。 参数:

s - 待搜索的整数。
arr - 整数切片,将被搜索。

返回值:

如果找到 s 在 arr 中,则返回 true;否则返回 false。

Deprecated: 使用 Contains

func SearchStringSlice deprecated

func SearchStringSlice(key string, arr []string) bool

Deprecated: 使用 Contains

func Searchslice

func Searchslice(s string, o []string) bool

Searchslice 在切片中判断某个值是否存在 Deprecated: 使用 Contains

func Slice2Map

func Slice2Map[Key comparable, Elem any](slice []Elem, keyFunc func(Elem) Key) map[Key]Elem

Slice2Map 更清晰的参数命名

func Slice2MapWithHeader

func Slice2MapWithHeader(rows any, header []string) map[string]any

Slice2MapWithHeader 主要是将excel 或者 csv的每一行转为map,键为header,值为cell

func SliceToAny

func SliceToAny[T any](slice []T) []any

SliceToAny 泛型版本,适用于各种切片类型 将指定类型的切片转成[]any

func SliceToMultiMap

func SliceToMultiMap[Key comparable, Elem any](slice []Elem, keyFunc func(Elem) Key) map[Key][]Elem

SliceToMultiMap 将切片转换为映射,允许键重复,相同键的值会保存在切片中 slice: 要转换的切片 keyFunc: 从元素中提取键的函数

func SnakeString

func SnakeString(s string) string

SnakeString 将驼峰命名法的字符串转换为蛇形命名法(小写字母加下划线)

func SortSlice

func SortSlice[T Ordered](slice []T, order config.SortType)

SortSlice 对 Ordered 类型的切片进行排序

func Str2StrSlice

func Str2StrSlice(values string) ([]string, error)

Str2StrSlice 字符串转切片

func StrToFloat64

func StrToFloat64(s string) (float64, error)

StrToFloat64 字符串转 float 64

func String2Float64

func String2Float64(v string) (float64, error)

func String2Int

func String2Int[T constraints.Integer](v string) (T, error)

func String2Int64

func String2Int64(v string) (int64, error)

String2Int64 将字符串转换为 int64 Deprecated: 请使用 String2Int

func StringUniq

func StringUniq(tmp []string) []string

StringUniq 对字符串切片进行去重

func Struct2Map

func Struct2Map(src any) map[string]any

Struct2Map 将结构体转换为map

func SumSlice

func SumSlice[T Ordered](slice []T) T

func Ternary

func Ternary[Type any](condition bool, a, b Type) Type

Ternary 是一个通用的三元运算函数。 它接受一个布尔条件和两个参数 a 和 b。 如果条件为 true,则返回 a;否则返回 b。

func ToBraceSyntax

func ToBraceSyntax(path string) (string, error)

ToBraceSyntax 将 :field 和 *field 格式转换为 {field} 和 {*field} 格式 输入示例: "/users/:id/profile/*filepath" -> "/users/{id}/profile/{*filepath}"

func ToHttpRouterSyntax

func ToHttpRouterSyntax(path string) (string, error)

ToHttpRouterSyntax 将 {field} 和 {*field} 格式转换为 :field 和 *field 格式 输入示例: "/users/{id}/profile/{*filepath}" -> "/users/:id/profile/*filepath"

func ToPtr

func ToPtr[T any](v T) *T

func TrimStringHelper

func TrimStringHelper(v string) string

func Uint16ToBytes

func Uint16ToBytes(n int) ([]byte, error)

func Uint32ToBytes

func Uint32ToBytes(n int) ([]byte, error)

func Uint64tostring

func Uint64tostring(i uint64) string

Uint64tostring uint64 转 string noinspection SpellCheckingInspection

func UrlEncode

func UrlEncode(url string) string

UrlEncode 将 query部分进行 url encode

func WaitForCondition

func WaitForCondition(ctx context.Context, condition func() bool) bool

Types

type Number

type Number interface {
	constraints.Integer | constraints.Float
}

Number 使用 constraints 包简化类型约束

type Ordered

type Ordered interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~float32 | ~float64 | ~string
}

Ordered 约束,表示可排序的类型

type Rangeable

type Rangeable[Idx comparable, V any, C comparable] interface {
	Range(func(Idx, V))
	Len() int
	ExtractKey(V) C
}

Rangeable 定义可用于range的接口 Idx: 集合的键类型(数组索引、map键等) V: 元素值类型 C: 用于比较的键类型 noinspection all

type ReadRowCallback

type ReadRowCallback func(scanner *bufio.Scanner) error

type RetryCallbackFunc

type RetryCallbackFunc func() error

type TimePrecision

type TimePrecision int

TimePrecision 表示时间精度

const (
	PrecisionYear    TimePrecision // 1
	PrecisionMonth                 // 2
	PrecisionWeek                  // 3
	PrecisionDay                   // 4
	PrecisionHour                  // 5
	PrecisionMinute                // 6
	PrecisionSecond                // 7
	PrecisionUnknown               // 8
)

func GetPrecisionFromFormat

func GetPrecisionFromFormat(format string) TimePrecision

GetPrecisionFromFormat 根据时间格式字符串获取时间精度

func (TimePrecision) IsSameTimePrecision

func (tp TimePrecision) IsSameTimePrecision(t1, t2 time.Time) bool

IsSameTimePrecision 方法实现时间精度比较

func (TimePrecision) TimeFormat

func (tp TimePrecision) TimeFormat(t time.Time) string

Directories

Path Synopsis
decode
Package retention 是用在自动清理数据的场景。
Package retention 是用在自动清理数据的场景。
Package ringbuffer 提供线程安全的智能环形缓冲区
Package ringbuffer 提供线程安全的智能环形缓冲区
calculator
Package calculator 定义环形缓冲区索引计算策略
Package calculator 定义环形缓冲区索引计算策略
impl
Package impl 实现环形缓冲区的数组存储版本
Package impl 实现环形缓冲区的数组存储版本
tree

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL