Documentation
¶
Overview ¶
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-09 01:15:55 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-09 01:05:55 * @FilePath: \go-toolbox\pkg\convert\bytes.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-09 01:00:55 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-09 01:00:55 * @FilePath: \go-toolbox\pkg\convert\ip.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-05-08 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-05-08 15:15:16 * @FilePath: \go-toolbox\pkg\convert\json_slice.go * @Description: 切片与JSON字符串互转工具 * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-01-13 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-01-13 10:16:15 * @FilePath: \go-toolbox\pkg\convert\kvpairs.go * @Description: 键值对转换工具 - 通用的 map 与可变参数互转 * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-08-03 21:32:26 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-05-27 18:09:55 * @FilePath: \go-toolbox\pkg\convert\must.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-02-28 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-02-28 00:00:00 * @FilePath: \go-toolbox\pkg\convert\object.go * @Description: 对象解析和转换工具 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-09 01:15:55 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-09 12:22:59 * @FilePath: \go-toolbox\pkg\convert\radix.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-06-09 01:15:55 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-06-20 13:22:11 * @FilePath: \go-toolbox\pkg\convert\reflect.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
Index ¶
- Variables
- func AddKVPair(kvs []interface{}, key string, value interface{}) []interface{}
- func AddKVPairs(kvs []interface{}, m map[string]interface{}) []interface{}
- func AnySliceToInterfaceSlice(slice any) []any
- func AppendValue(buf []byte, v any) []byte
- func B2S(b []byte) string
- func B64Decode(s string) ([]byte, error)
- func B64Encode(data interface{}) (string, error)
- func B64ToByte(imageBase64 string) ([]byte, error)
- func B64UrlDecode(s string) ([]byte, error)
- func B64UrlEncode(data interface{}) (string, error)
- func ByteToBinStr(b byte) string
- func BytesToBCC(data []byte) byte
- func BytesToBinStr(bs []byte) string
- func BytesToBinStrWithSplit(bs []byte, split string) string
- func BytesToHex(data []byte) string
- func DecToBin(n uint64) string
- func DecToHex(n uint64) string
- func Float64ToInt[T types.Numerical](value float64, mode RoundMode) (T, error)
- func FormatCount(value any) string
- func FormatDuration(value any) string
- func FormatPercentage(value any, precision int) string
- func HexToBCC(hexStr string) (string, error)
- func HexToBin(h string) (string, error)
- func HexToBytes(hexStr string) ([]byte, error)
- func HexToDec(h string) (uint64, error)
- func IP2Long(ip net.IP) (uint, error)
- func InterfaceMapToStringMap(m map[any]any) map[string]any
- func InterfaceSliceToIntSlice(slice []any, mode *RoundMode) []int
- func InterfaceSliceToStringSlice(slice []any) []string
- func InterfaceToYAML(data interface{}) ([]byte, error)
- func JSONStringToYAML(jsonStr string) (string, error)
- func JSONToYAML(jsonData []byte) ([]byte, error)
- func KVPairs(keysAndValues ...interface{}) []interface{}
- func KVPairsToMap(keysAndValues []interface{}) map[string]interface{}
- func Long2IP(i uint) (net.IP, error)
- func MapAnyToKVPairs(m map[string]any) []any
- func MapStringToKVPairs(m map[string]string) []interface{}
- func MapToKVPairs(m map[string]interface{}) []interface{}
- func MapToYAML(data map[string]interface{}) ([]byte, error)
- func MarshalJSON[T any](data T) ([]byte, error)
- func MarshalYAML[T any](data T) ([]byte, error)
- func MergeKVPairs(kvSlices ...[]interface{}) []interface{}
- func MergeMapToKVPairs(maps ...map[string]interface{}) []interface{}
- func MustBool[T any](v T) bool
- func MustConvertTo[T types.Convertible](value any) (T, bool)
- func MustFloatT[T types.Float](value any, mode RoundMode) (T, error)
- func MustIntT[T types.Numerical](value any, mode *RoundMode) (T, error)
- func MustJSON(v any) ([]byte, error)
- func MustJSONIndent(v any) ([]byte, error)
- func MustString[T any](v T, timeLayout ...string) string
- func MustToNumberSlice[T types.Numerical](input any, desolator string) []T
- func NumberSliceToStringSlice[T types.Numerical](numbers []T) []string
- func ParseFloat[T types.Float](v string, value *T) error
- func ParseKVPairsToMap(keysAndValues ...any) map[string]any
- func ParseObjectToMap(obj any) map[string]any
- func S2B(s string) []byte
- func SliceByteToString(b []byte) string
- func StringSliceToFloatSlice[T types.Float](input []string, mode RoundMode) ([]T, error)
- func StringSliceToInterfaceSlice(slice []string) []any
- func StringSliceToNumberSlice[T types.Numerical](input []string, mode *RoundMode) ([]T, error)
- func StringsFromJSON(jsonStr string) ([]string, error)
- func StringsToJSON(s []string) string
- func ToFloat64(value any) (float64, error)
- func ToNumberSlice[T types.Numerical](input any, desolator string) ([]T, error)
- func TransformFields(dst any, src any, opts *TransformFieldsOptions) error
- func UnmarshalJSON[T any](jsonData []byte) (*T, error)
- func UnmarshalYAML[T any](yamlData []byte) (*T, error)
- func YAMLStringToJSON(yamlStr string) (string, error)
- func YAMLToInterface(yamlData []byte) (interface{}, error)
- func YAMLToJSON(yamlData []byte) ([]byte, error)
- func YAMLToMap(yamlData []byte) (map[string]interface{}, error)
- type ConvertError
- type RoundMode
- type TransformFieldsOptions
- type Transformer
- func (t *Transformer) GetDst() any
- func (t *Transformer) GetOptions() *TransformFieldsOptions
- func (t *Transformer) GetSrc() any
- func (t *Transformer) SetDst(dst any) *Transformer
- func (t *Transformer) SetOptions(opts *TransformFieldsOptions) *Transformer
- func (t *Transformer) SetSrc(src any) *Transformer
- func (t *Transformer) Transform() error
Constants ¶
This section is empty.
Variables ¶
var ( ErrDstNilPointer = errors.New("dst must be a non-nil pointer") ErrDstNil = errors.New("dst must not be nil") ErrSrcNil = errors.New("src must not be nil") ErrTypeMismatchStrict = "type mismatch: cannot assign %s to %s" ErrUnsupportedType = "unsupported or mismatched type: %s -> %s" ErrNegativeIntToUint = "negative int %d cannot assign to %s" ErrTypeMismatchToBool = "type mismatch: cannot assign %s to bool" ErrTypeMismatchToString = "type mismatch: cannot assign %s to string" ErrTypeMismatchToSlice = "type mismatch: cannot assign %s to slice %s" ErrTypeMismatchToMap = "type mismatch: cannot assign %s to map %s" )
错误信息常量,方便统一维护和复用
Functions ¶
func AddKVPair ¶
func AddKVPair(kvs []interface{}, key string, value interface{}) []interface{}
AddKVPair 向现有键值对切片添加一个新的键值对 提供便捷的追加方式
使用示例:
kvs := []interface{}{"user_id", "123"}
kvs = convert.AddKVPair(kvs, "action", "login")
kvs = []interface{}{"user_id", "123", "action", "login"}
func AddKVPairs ¶
func AddKVPairs(kvs []interface{}, m map[string]interface{}) []interface{}
AddKVPairs 向现有键值对切片批量添加键值对 支持从 map 添加
使用示例:
kvs := []interface{}{"user_id", "123"}
extraFields := map[string]interface{}{"action": "login", "ip": "127.0.0.1"}
kvs = convert.AddKVPairs(kvs, extraFields)
func AnySliceToInterfaceSlice ¶
AnySliceToInterfaceSlice 将任意类型的切片或数组转换为 []any 支持所有类型切片: []string, []int, []int32, []int64, []uint, []bool, 自定义类型切片等 支持数组类型: [3]int, [5]string 等 如果传入的不是切片/数组类型或为空,返回空切片
func AppendValue ¶
AppendValue 高效地将值追加到缓冲区 支持所有 Go 内置类型的零拷贝追加
func B2S ¶
B2S converts byte slice to string without a memory allocation. Slower: unsafe.String(unsafe.SliceData(b), len(b)) strings.Clone(): unsafe.String(&b[0], len(b))
func B64UrlEncode ¶
B64UrlEncode Base64 URL 安全编码
func BytesToBinStrWithSplit ¶
BytesToBinStrWithSplit 将字节数组转换为二进制字符串,并添加分隔符
func Float64ToInt ¶
Float64ToInt 将浮点数转换为整数类型,进行范围检查
func FormatCount ¶
FormatCount 格式化数量(处理 nil 值) 将数量值格式化为字符串,nil 值返回 "0"
参数:
- value: 数量值(any 类型,支持各种数值类型)
返回:
- 格式化后的字符串
- 如果值为 nil,返回 "0"
示例:
- FormatCount(123) -> "123"
- FormatCount(nil) -> "0"
- FormatCount(0) -> "0"
func FormatDuration ¶
FormatDuration 格式化时长(秒 -> 人类可读格式) 根据时长自动选择合适的单位(年、月、日、时、分、秒)
参数:
- value: 时长值(any 类型,支持 float64、int、int64 等)
返回:
- 格式化后的字符串
- 如果值为 nil 或 <= 0,返回 "N/A"
时间单位换算:
- 1 分钟 = 60 秒
- 1 小时 = 3600 秒
- 1 天 = 86400 秒
- 1 月 = 2592000 秒(30天)
- 1 年 = 31536000 秒(365天)
示例:
- FormatDuration(45) -> "45s"
- FormatDuration(90) -> "1m 30s"
- FormatDuration(3665) -> "1h 1m 5s"
- FormatDuration(86400) -> "1d"
- FormatDuration(2678400) -> "1mo"
- FormatDuration(31536000) -> "1y"
- FormatDuration(nil) -> "N/A"
func FormatPercentage ¶
FormatPercentage 格式化百分比 将浮点数格式化为百分比字符串
参数:
- value: 百分比值(any 类型,支持 float64、int 等)
- precision: 小数位数(默认 1)
返回:
- 格式化后的百分比字符串(如 "85.5%")
- 如果值为 nil,返回 "0%"
示例:
- FormatPercentage(85.567, 1) -> "85.6%"
- FormatPercentage(nil, 1) -> "0%"
- FormatPercentage(100, 0) -> "100%"
func HexToBytes ¶
HexToBytes 将十六进制字符串转换为字节数组。 如果十六进制字符串的长度为奇数或转换失败,则返回错误。
func InterfaceMapToStringMap ¶
InterfaceMapToStringMap 将 map[any]any 转换为 map[string]any
func InterfaceSliceToIntSlice ¶
InterfaceSliceToIntSlice 将 []any 转换为 []int
func InterfaceSliceToStringSlice ¶
InterfaceSliceToStringSlice 将 []any 转换为 []string
func InterfaceToYAML ¶
InterfaceToYAML 将 interface{} 转换为 YAML 字节数组
func JSONStringToYAML ¶
JSONStringToYAML 将 JSON 字符串转换为 YAML 字符串
func JSONToYAML ¶
JSONToYAML 将 JSON 字节数组转换为 YAML 字节数组
func KVPairs ¶
func KVPairs(keysAndValues ...interface{}) []interface{}
KVPairs 快速创建键值对切片的辅助函数 用于内联创建参数列表,提供更清晰的语义
使用示例:
构建参数列表
params := convert.KVPairs("user_id", "123", "action", "login")
用于函数调用
someFunc("消息", convert.KVPairs("key1", "val1", "key2", "val2")...)
提供变量存储
fields := convert.KVPairs("status", "active", "count", 100)
注意:此函数主要提供语义清晰性,实际上不做任何转换, 相当于类型别名和文档说明
func KVPairsToMap ¶
func KVPairsToMap(keysAndValues []interface{}) map[string]interface{}
KVPairsToMap 将键值对切片转换回 map[string]interface{} 与 MapToKVPairs 相反的操作
使用示例:
kvs := []interface{}{"key1", "value1", "key2", 123}
m := convert.KVPairsToMap(kvs)
m = map[string]interface{}{"key1": "value1", "key2": 123}
func MapAnyToKVPairs ¶
MapAnyToKVPairs 将 map[string]any 转换为键值对切片(Go 1.18+ 泛型版本) any 是 interface{} 的别名,此函数提供更现代的 API
func MapStringToKVPairs ¶
MapStringToKVPairs 将 map[string]string 转换为键值对切片 针对字符串 map 的优化版本
使用示例:
headers := map[string]string{
"Content-Type": "application/json",
"Authorization": "Bearer token",
}
用于只接受可变参数的函数
someFunc("处理请求", convert.MapStringToKVPairs(headers)...)
用于构建参数列表
params := convert.MapStringToKVPairs(headers)
func MapToKVPairs ¶
func MapToKVPairs(m map[string]interface{}) []interface{}
MapToKVPairs 将 map[string]interface{} 转换为键值对切片 用于将 map 转换为可变参数格式(...interface{})
适用场景:
- 调用不支持直接传 map 的 API
- 需要与键值对切片进行合并操作
- 构建动态参数列表
使用示例:
fields := map[string]interface{}{
"user_id": "123",
"action": "login",
}
场景1: 调用只接受可变参数的函数
someFunc("message", convert.MapToKVPairs(fields)...)
场景2: 与其他键值对合并
base := []interface{}{"tenant_id", "678"}
all := convert.MergeKVPairs(base, convert.MapToKVPairs(fields))
func MarshalJSON ¶
MarshalJSON 泛型 JSON 序列化(复用现有 json 包功能)
func MergeKVPairs ¶
func MergeKVPairs(kvSlices ...[]interface{}) []interface{}
MergeKVPairs 合并多个键值对切片 用于组合多个字段或参数列表
使用示例:
baseFields := []interface{}{"user_id", "123", "tenant_id", "678"}
extraFields := []interface{}{"action", "login", "ip", "192.168.1.1"}
allFields := convert.MergeKVPairs(baseFields, extraFields)
用于函数调用
someFunc("消息", allFields...)
map 和切片
mapFields := map[string]interface{}{"status": "ok"}
merged := convert.MergeKVPairs(baseFields, convert.MapToKVPairs(mapFields))
func MergeMapToKVPairs ¶
func MergeMapToKVPairs(maps ...map[string]interface{}) []interface{}
MergeMapToKVPairs 合并多个 map 并转换为键值对切片 简化多个 map 合并并转换为可变参数的操作
使用示例:
基础字段和额外字段合并
baseFields := map[string]interface{}{"event": "login", "user_id": "123"}
extraFields := map[string]interface{}{"ip": "127.0.0.1", "device": "mobile"}
kvs := convert.MergeMapToKVPairs(baseFields, extraFields)
合并多个 map
kvs := convert.MergeMapToKVPairs(map1, map2, map3)
func MustConvertTo ¶
func MustConvertTo[T types.Convertible](value any) (T, bool)
MustConvertTo 通用的泛型类型转换函数 自动将 value 转换为目标类型 T
参数:
- value: 要转换的值
返回值:
- 转换后的值和是否成功的标志
支持的类型:
- string: 字符串
- bool: 布尔值
- int, int8, int16, int32, int64: 有符号整数
- uint, uint8, uint16, uint32, uint64: 无符号整数
- float32, float64: 浮点数
- []byte: 字节切片
- map[string]any: 字典类型
- []any: 切片类型
示例:
str, ok := MustConvertTo[string](123) // "123", true
num, ok := MustConvertTo[int]("567") // 567, true
flag, ok := MustConvertTo[bool]("true") // true, true
f64, ok := MustConvertTo[float64]("3.14") // 3.14, true
bytes, ok := MustConvertTo[[]byte]("hello") // []byte("hello"), true
m, ok := MustConvertTo[map[string]any](data) // map, true
func MustFloatT ¶
MustFloatT 将值转换为浮点数类型 T 参数:
- value: 要转换的值,支持 string、float 系列、int 系列
- mode: 取整模式
返回值: 转换后的浮点数和可能的错误
func MustIntT ¶
MustIntT 将任意类型转换为数字类型 T 参数:
- value: 要转换的值,支持 int/uint 系列、float 系列、string
- mode: 取整模式,nil 时默认为 RoundDown
返回值: 转换后的数字和可能的错误
func MustString ¶
MustString 强制转为字符串 参数:
- v: 要转换的值,支持 string、[]byte、error、bool、数字、time.Time 等
- timeLayout: 可选的时间格式化布局,默认使用 time.RFC3339
返回值: 转换后的字符串
func MustToNumberSlice ¶
MustToNumberSlice 不返回错误的版本,转换失败时 panic
func NumberSliceToStringSlice ¶
NumberSliceToStringSlice Number切片转String
func ParseFloat ¶
ParseFloat 将字符串解析为浮点数,进行 NaN 和 Inf 检查
func ParseKVPairsToMap ¶
ParseKVPairsToMap 解析键值对参数为 map 支持: - 键值对:key1, value1, key2, value2 - 单个对象:struct 或 map[string]any
func ParseObjectToMap ¶
ParseObjectToMap 解析对象为 key-value map 支持 struct、map[string]any、map[string]any
func S2B ¶
S2B converts string to byte slice without a memory allocation. Ref: https://github.com/golang/go/issues/53003#issuecomment-1140276077
func SliceByteToString ¶
SliceByteToString 将字节切片转换为字符串(零拷贝)
注意:返回的 string 与 b 共享底层数组,修改 b 会影响返回值 仅适用于只读场景或临时字符串
func StringSliceToFloatSlice ¶
StringSliceToFloatSlice 将字符串切片转换为浮点数切片
同 StringSliceToNumberSlice,绕开 MustFloatT 的 any 入参以免逐元素装箱
func StringSliceToInterfaceSlice ¶
StringSliceToInterfaceSlice 将 []string 转换为 []any 为了向后兼容保留,内部调用 AnySliceToInterfaceSlice
func StringSliceToNumberSlice ¶
StringSliceToNumberSlice 将字符串切片转换为数字切片
直接走字符串特化的解析,不再绕 MustIntT
MustIntT 的入参是 any,而这里静态上已经知道元素是 string把 string 放进 any 会分配一次(字符串头装不进一个接口字),于是每个元素都要多付一次分配, 再加一次 reflect.ValueOf 与 Kind 分支——泛型函数本来握着类型信息,却在调用 MustIntT 时丢掉了 十个元素实测由 247ns / 11 次分配降到 135ns / 1 次分配,只剩结果切片那一次
[EN] Parses with the string-specialised path instead of going through MustIntT, whose parameter is any. The element type is statically known to be string here, and putting a string into an any allocates — a string header does not fit in one interface word — so every element paid an allocation plus a reflect.ValueOf and Kind switch. A generic function holds the type information and threw it away at the call. Measured over ten elements, 247ns and 11 allocations become 135ns and the single allocation for the result slice
func StringsFromJSON ¶
StringsFromJSON 将JSON数组字符串反序列化为字符串切片 空字符串返回nil
func StringsToJSON ¶
StringsToJSON 将字符串切片序列化为JSON数组字符串 空切片返回空字符串
func ToNumberSlice ¶
ToNumberSlice 支持输入 string 或 []string,自动拆分和转换 参数:
- input: 字符串或字符串切片
- desolator: 分隔符(仅当 input 为 string 时有效)
返回值: 数字切片和可能的错误
func TransformFields ¶
func TransformFields(dst any, src any, opts *TransformFieldsOptions) error
TransformFields 兼容旧用法,返回 error
func UnmarshalJSON ¶
UnmarshalJSON 泛型 JSON 反序列化(复用现有 json 包功能)
func UnmarshalYAML ¶
UnmarshalYAML 泛型 YAML 反序列化
func YAMLStringToJSON ¶
YAMLStringToJSON 将 YAML 字符串转换为 JSON 字符串
func YAMLToInterface ¶
YAMLToInterface 将 YAML 字节数组解析为 interface{}
func YAMLToJSON ¶
YAMLToJSON 将 YAML 字节数组转换为 JSON 字节数组
Types ¶
type ConvertError ¶
ConvertError 用于包装转换过程中产生的错误
type TransformFieldsOptions ¶
type TransformFieldsOptions struct {
StrictTypeCheck bool // 是否严格类型检查,默认 false
TimeFormat string // 时间格式,默认 time.DateTime
TransTagName string // 支持字段标签名
}
TransformFieldsOptions 定义转换选项
func (*TransformFieldsOptions) SetStrictTypeCheck ¶
func (o *TransformFieldsOptions) SetStrictTypeCheck(strict bool) *TransformFieldsOptions
SetStrictTypeCheck 设置严格类型检查
func (*TransformFieldsOptions) SetTimeFormat ¶
func (o *TransformFieldsOptions) SetTimeFormat(format string) *TransformFieldsOptions
SetTimeFormat 设置时间格式
type Transformer ¶
type Transformer struct {
// contains filtered or unexported fields
}
Transformer 负责执行转换操作,封装目标对象、源数据及转换选项
func (*Transformer) GetOptions ¶
func (t *Transformer) GetOptions() *TransformFieldsOptions
GetOptions 获取转换选项,线程安全
func (*Transformer) SetDst ¶
func (t *Transformer) SetDst(dst any) *Transformer
SetDst 设置目标结构体指针,必须是非 nil 指针
func (*Transformer) SetOptions ¶
func (t *Transformer) SetOptions(opts *TransformFieldsOptions) *Transformer
SetOptions 设置转换选项,支持链式调用
func (*Transformer) SetSrc ¶
func (t *Transformer) SetSrc(src any) *Transformer
SetSrc 设置源数据,支持结构体、map 等
func (*Transformer) Transform ¶
func (t *Transformer) Transform() error
Transform 执行转换操作,将源数据转换到目标对象,返回转换过程中的错误 该方法使用带尝试加锁的方式保证并发安全,未能获取锁时返回 ErrLockNotAcquired