utils

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2025 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package utils 提供通用工具函数。

核心功能:

  • 字符串、切片、Map 操作
  • 时间、数字处理
  • 指针辅助、异步工具
  • ID 生成(UUID/Snowflake)

使用示例:

id := utils.UUID()
ptr := utils.Ptr("value")
result := utils.Map(slice, func(v int) int { return v * 2 })

Index

Constants

View Source
const (
	DateFormat     = "2006-01-02"
	TimeFormat     = "15:04:05"
	DateTimeFormat = "2006-01-02 15:04:05"
	ISO8601Format  = "2006-01-02T15:04:05Z07:00"
)

常用时间格式

Variables

This section is empty.

Functions

func Abs

func Abs[T constraints.Signed | constraints.Float](n T) T

Abs 绝对值

func Age

func Age(birthday time.Time) int

Age 计算年龄

func All

func All[T any](slice []T, predicate func(T) bool) bool

All 检查所有元素是否满足条件

func Any

func Any[T any](slice []T, predicate func(T) bool) bool

Any 检查是否有元素满足条件

func Avg

func Avg[T constraints.Integer | constraints.Float](nums ...T) float64

Avg 求平均值

func BytesToString

func BytesToString(b []byte) string

BytesToString 零拷贝字节切片转字符串

func Chunk

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

Chunk 分块

func Clamp

func Clamp[T constraints.Ordered](value, min, max T) T

Clamp 限制值在范围内

func Contains

func Contains[T comparable](slice []T, item T) bool

Contains 检查切片是否包含元素

func DaysBetween

func DaysBetween(t1, t2 time.Time) int

DaysBetween 计算两个时间相差的天数

func Debounce

func Debounce(fn func(), delay time.Duration) func()

Debounce 防抖

func DefaultIfBlank

func DefaultIfBlank(s, defaultVal string) string

DefaultIfBlank 如果为空白则返回默认值

func DefaultIfEmpty

func DefaultIfEmpty(s, defaultVal string) string

DefaultIfEmpty 如果为空则返回默认值

func EndOfDay

func EndOfDay(t time.Time) time.Time

EndOfDay 获取当天结束时间

func EndOfMonth

func EndOfMonth(t time.Time) time.Time

EndOfMonth 获取本月结束时间

func Filter

func Filter[T any](slice []T, predicate func(T) bool) []T

Filter 过滤

func FilterMap

func FilterMap[K comparable, V any](m map[K]V, predicate func(K, V) bool) map[K]V

FilterMap 过滤 map

func Find

func Find[T any](slice []T, predicate func(T) bool) (T, bool)

Find 查找第一个匹配元素

func FindIndex

func FindIndex[T any](slice []T, predicate func(T) bool) int

FindIndex 查找第一个匹配元素的索引

func First

func First[T any](slice []T) (T, bool)

First 返回第一个元素

func Flatten

func Flatten[T any](slices [][]T) []T

Flatten 扁平化

func FormatDate

func FormatDate(t time.Time) string

FormatDate 格式化日期

func FormatDateTime

func FormatDateTime(t time.Time) string

FormatDateTime 格式化日期时间

func FormatISO8601

func FormatISO8601(t time.Time) string

FormatISO8601 格式化为 ISO8601

func FormatTime

func FormatTime(t time.Time) string

FormatTime 格式化时间

func FromUnixMilli

func FromUnixMilli(ms int64) time.Time

FromUnixMilli 从毫秒时间戳创建时间

func GetOrDefault

func GetOrDefault[K comparable, V any](m map[K]V, key K, defaultVal V) V

GetOrDefault 获取值,不存在返回默认值

func GroupBy

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

GroupBy 分组

func InRange

func InRange[T constraints.Ordered](value, min, max T) bool

InRange 检查值是否在范围内 [min, max]

func IndexOf

func IndexOf[T comparable](slice []T, item T) int

IndexOf 返回元素索引,不存在返回 -1

func Invert

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

Invert 反转 map(键值互换)

func IsBlank

func IsBlank(s string) bool

IsBlank 检查字符串是否为空或只包含空白字符

func IsEmpty

func IsEmpty(s string) bool

IsEmpty 检查字符串是否为空

func IsEven

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

IsEven 是否为偶数

func IsNegative

func IsNegative[T constraints.Signed | constraints.Float](n T) bool

IsNegative 是否为负数

func IsNil

func IsNil[T any](p *T) bool

IsNil 检查指针是否为 nil

func IsNotBlank

func IsNotBlank(s string) bool

IsNotBlank 检查字符串是否非空且不只包含空白字符

func IsNotEmpty

func IsNotEmpty(s string) bool

IsNotEmpty 检查字符串是否非空

func IsNotNil

func IsNotNil[T any](p *T) bool

IsNotNil 检查指针是否非 nil

func IsOdd

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

IsOdd 是否为奇数

func IsPositive

func IsPositive[T constraints.Signed | constraints.Float](n T) bool

IsPositive 是否为正数

func IsSameDay

func IsSameDay(t1, t2 time.Time) bool

IsSameDay 是否是同一天

func IsToday

func IsToday(t time.Time) bool

IsToday 是否是今天

func IsWeekend

func IsWeekend(t time.Time) bool

IsWeekend 是否是周末

func IsYesterday

func IsYesterday(t time.Time) bool

IsYesterday 是否是昨天

func IsZero

func IsZero[T constraints.Integer | constraints.Float](n T) bool

IsZero 是否为零

func Keys

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

Keys 返回 map 的所有键

func Last

func Last[T any](slice []T) (T, bool)

Last 返回最后一个元素

func Map

func Map[T, R any](slice []T, mapper func(T) R) []R

Map 映射转换

func MapKeys

func MapKeys[K1, K2 comparable, V any](m map[K1]V, mapper func(K1) K2) map[K2]V

MapKeys 转换 map 的键

func MapValues

func MapValues[K comparable, V1, V2 any](m map[K]V1, mapper func(V1) V2) map[K]V2

MapValues 转换 map 的值

func MaskEmail

func MaskEmail(email string) string

MaskEmail 邮箱脱敏 (t***@example.com)

func MaskIDCard

func MaskIDCard(idCard string) string

MaskIDCard 身份证脱敏 (110***********1234)

func MaskPhone

func MaskPhone(phone string) string

MaskPhone 手机号脱敏 (138****1234)

func Max

func Max[T constraints.Ordered](a, b T) T

Max 返回最大值

func MaxSlice

func MaxSlice[T constraints.Ordered](nums []T) (T, bool)

MaxSlice 切片最大值

func Merge

func Merge[K comparable, V any](maps ...map[K]V) map[K]V

Merge 合并多个 map(后者覆盖前者)

func Min

func Min[T constraints.Ordered](a, b T) T

Min 返回最小值

func MinSlice

func MinSlice[T constraints.Ordered](nums []T) (T, bool)

MinSlice 切片最小值

func NanoID

func NanoID() string

NanoID 生成 NanoID(默认 21 位)

func Omit

func Omit[K comparable, V any](m map[K]V, keys ...K) map[K]V

Omit 排除指定键

func OrderedID

func OrderedID() string

OrderedID 生成有序 ID(时间戳 + 随机数)

func Parallel

func Parallel(fns ...func() error) error

Parallel 并行执行多个函数

func ParallelWithContext

func ParallelWithContext(ctx context.Context, fns ...func(context.Context) error) error

ParallelWithContext 带 context 的并行执行

func ParseDate

func ParseDate(s string) (time.Time, error)

ParseDate 解析日期

func ParseDateTime

func ParseDateTime(s string) (time.Time, error)

ParseDateTime 解析日期时间

func ParseISO8601

func ParseISO8601(s string) (time.Time, error)

ParseISO8601 解析 ISO8601

func Pick

func Pick[K comparable, V any](m map[K]V, keys ...K) map[K]V

Pick 选取指定键

func Ptr

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

Ptr 返回值的指针

func RandomBase64

func RandomBase64(length int) string

RandomBase64 生成 Base64 编码的随机字符串

func RandomID

func RandomID(length int) string

RandomID 生成随机 ID(指定长度的十六进制字符串)

func Reduce

func Reduce[T, R any](slice []T, initial R, reducer func(R, T) R) R

Reduce 归约

func Retry

func Retry(ctx context.Context, fn func() error, cfg RetryConfig) error

Retry 重试执行函数

func RetryWithResult

func RetryWithResult[T any](ctx context.Context, fn func() (T, error), cfg RetryConfig) (T, error)

RetryWithResult 重试执行带返回值的函数

func Reverse

func Reverse(s string) string

Reverse 反转字符串

func ReverseSlice

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

Reverse 反转切片

func SetSnowflakeNode

func SetSnowflakeNode(nodeID int64)

SetSnowflakeNode 设置雪花 ID 节点

func ShortID

func ShortID(length int) string

ShortID 生成短 ID(指定长度,使用 62 进制字符)

func Snowflake

func Snowflake() int64

Snowflake 生成雪花 ID 格式: 41位时间戳 + 10位节点ID + 12位序列号

func SnowflakeString

func SnowflakeString() string

SnowflakeString 生成字符串格式的雪花 ID

func StartOfDay

func StartOfDay(t time.Time) time.Time

StartOfDay 获取当天开始时间

func StartOfMonth

func StartOfMonth(t time.Time) time.Time

StartOfMonth 获取本月开始时间

func StartOfWeek

func StartOfWeek(t time.Time) time.Time

StartOfWeek 获取本周开始时间(周一)

func StartOfYear

func StartOfYear(t time.Time) time.Time

StartOfYear 获取本年开始时间

func StringToBytes

func StringToBytes(s string) []byte

StringToBytes 零拷贝字符串转字节切片(只读)

func Sum

func Sum[T constraints.Integer | constraints.Float](nums ...T) T

Sum 求和

func Throttle

func Throttle(fn func(), interval time.Duration) func()

Throttle 节流

func ToCamelCase

func ToCamelCase(s string) string

ToCamelCase 转换为驼峰命名 (snake_case -> snakeCase)

func ToFloat64

func ToFloat64[T constraints.Integer | constraints.Float](n T) float64

ToFloat64 安全转换为 float64

func ToInt

func ToInt[T constraints.Integer | constraints.Float](n T) int

ToInt 安全转换为 int

func ToInt64

func ToInt64[T constraints.Integer | constraints.Float](n T) int64

ToInt64 安全转换为 int64

func ToPascalCase

func ToPascalCase(s string) string

ToPascalCase 转换为帕斯卡命名 (snake_case -> SnakeCase)

func ToSnakeCase

func ToSnakeCase(s string) string

ToSnakeCase 转换为蛇形命名 (camelCase -> camel_case)

func Truncate

func Truncate(s string, maxLen int) string

Truncate 截断字符串

func TruncateWithSuffix

func TruncateWithSuffix(s string, maxLen int, suffix string) string

TruncateWithSuffix 截断字符串并添加后缀

func UUID

func UUID() string

UUID 生成 UUID v4

func UUIDShort

func UUIDShort() string

UUIDShort 生成短 UUID(去掉横线)

func Unique

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

Unique 去重

func UnixMilli

func UnixMilli(t time.Time) int64

UnixMilli 获取毫秒时间戳

func Val

func Val[T any](p *T) T

Val 返回指针的值,nil 返回零值

func ValOr

func ValOr[T any](p *T, defaultVal T) T

ValOr 返回指针的值,nil 返回默认值

func Values

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

Values 返回 map 的所有值

func WithTimeout

func WithTimeout[T any](ctx context.Context, timeout time.Duration, fn func(context.Context) (T, error)) (T, error)

WithTimeout 带超时执行

Types

type Optional

type Optional[T any] struct {
	// contains filtered or unexported fields
}

Optional 可选值

func FlatMapOpt

func FlatMapOpt[T, R any](o Optional[T], mapper func(T) Optional[R]) Optional[R]

FlatMapOpt 扁平化转换

func MapOpt

func MapOpt[T, R any](o Optional[T], mapper func(T) R) Optional[R]

MapOpt 转换值

func None

func None[T any]() Optional[T]

None 创建空的 Optional

func OfNullable

func OfNullable[T any](p *T) Optional[T]

OfNullable 从指针创建 Optional

func Some

func Some[T any](v T) Optional[T]

Some 创建有值的 Optional

func (Optional[T]) Get

func (o Optional[T]) Get() T

Get 获取值(无值时 panic)

func (Optional[T]) IfPresent

func (o Optional[T]) IfPresent(consumer func(T))

IfPresent 如果有值则执行

func (Optional[T]) IsEmpty

func (o Optional[T]) IsEmpty() bool

IsEmpty 是否为空

func (Optional[T]) IsPresent

func (o Optional[T]) IsPresent() bool

IsPresent 是否有值

func (Optional[T]) OrElse

func (o Optional[T]) OrElse(defaultVal T) T

OrElse 获取值或默认值

func (Optional[T]) OrElseGet

func (o Optional[T]) OrElseGet(supplier func() T) T

OrElseGet 获取值或通过函数获取默认值

type RetryConfig

type RetryConfig struct {
	MaxAttempts int
	Delay       time.Duration
	MaxDelay    time.Duration
	Multiplier  float64
}

RetryConfig 重试配置

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig 默认重试配置

Jump to

Keyboard shortcuts

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