typex

package module
v1.26.4 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2026 License: Apache-2.0 Imports: 6 Imported by: 19

README

typex

泛型类型扩展库,提供枚举、链表、树、值类型等数据结构封装,零外部依赖,是整个 go-xuan 体系的唯一基础模块。

安装

go get github.com/go-xuan/typex

类型概览

Enum[K, V] — 并发安全的有序泛型 map

保证插入顺序,读写锁保护,支持遍历、快照和链式调用。

import "github.com/go-xuan/typex"

// 创建
enum := typex.NewStringEnum[string]()  // key 为 string
enum := typex.NewEnum[int, *User]()    // key 为任意 comparable 类型

// 写入
enum.Add("key1", "value1")
enum.Put("key2", "value2")   // Put 是 Add 的别名

// 读取
val := enum.Get("key1")              // 返回零值如果不存在
val, ok := enum.Exist("key1")        // 带 ok 的安全读取

// 删除 & 清空
enum.Remove("key1")
enum.Clear()

// 遍历(handle 返回 true 停止,false 继续)
enum.Range(func(k string, v string) bool {
    fmt.Println(k, v)
    return false // 继续遍历
})

// 带索引遍历
enum.RangeWithIndex(func(i int, k string, v string) bool {
    return false
})

// 批量获取
keys := enum.Keys()       // []string,按插入顺序
values := enum.Values()   // []string,按插入顺序
size := enum.Len()

支持头尾追加/删除,互斥锁保护。

list := typex.NewLink("first")
list.Append("second").Append("third")
head, _ := list.GetHead()  // "first"
tail, _ := list.GetTail()  // "third"
list.Remove()              // 删除尾节点
size := list.Size()        // 2
TreeNode[T] — 平铺数组转树形结构

将实现了 GetID()/GetPID() 的平铺列表转为嵌套树。

type Dept struct {
    Id       string
    ParentId string
    Name     string
}
func (d Dept) GetID() string  { return d.Id }
func (d Dept) GetPID() string { return d.ParentId }

depts := []Dept{{"1", "0", "总部"}, {"2", "1", "研发部"}}
tree := typex.Convert2Tree(depts, "0")  // "0" 为根节点 pid
typex.PrintTree(tree, "  ")            // 打印缩进树
Value — 多态值类型

统一包装 int/int64/float64/bool/string/time.Time,提供带默认值的类型转换。

// 自动推断类型
v := typex.NewValue(42)          // Int
v := typex.NewValue("hello")     // String
v := typex.NewValue(time.Now())  // Time
v := typex.NewValue(nil)         // Zero

// 带默认值的类型转换
v.String("default")     // 无效时返回 "default"
v.Int(-1)               // 无效时返回 -1
v.Int64(0)
v.Float64(0.0)
v.Bool(false)

// 专用构造函数
v := typex.NewInt(100)
v := typex.NewString("text")
v := typex.NewTime(time.Now())
v := typex.NewZero()     // 始终无效的值

v.Valid()                // 判断是否有效
v.Cover(anotherValue)    // 覆盖当前值
Args — 参数收集器

实现 Collect[string, Value] 接口,支持 JSON 反序列化。

args := typex.Args{
    "name": typex.NewString("Alice"),
    "age":  typex.NewInt(30),
}
name := args.Get("name").String()
age := args.Get("age").Int()

// JSON 反序列化(自动推断 value 类型)
json.Unmarshal([]byte(`{"key": "val", "num": 42}`), &args)

// 遍历
typex.ArgsRange(args, func(k string, v typex.Value) {
    fmt.Println(k, v.String())
})
Collect[K, V] — 收集器接口

简单的 Put/Get 抽象,EnumArgs 均实现了该接口。

type Collect[K comparable, V any] interface {
    Put(k K, v V)
    Get(k K) V
}

// 类型别名
typex.CollectAny     // Collect[string, any]
typex.CollectString  // Collect[string, string]
typex.CollectValue   // Collect[string, Value]
Set[T] — 并发安全的泛型集合
s := typex.NewSet[string]()
s.Add("a")
s.Add("b")
s.Has("a")       // true
s.Remove("a")
s.Len()          // 1
s.Clear()

// 遍历(handle 返回 false 停止,与 sync.Map.Range 一致)
s.Range(func(v string) bool {
    fmt.Println(v)
    return true // 继续遍历
})

slice := s.ToSlice()  // []string
JSON — JSON 编解码接口
type JSON interface {
    MarshalJSON() ([]byte, error)
    UnmarshalJSON([]byte) error
}

完整方法速查

类型 方法
Enum[K,V] Add, Put, Get, Exist, Remove, Clear, Keys, Values, Len, Range, RangeWithIndex
Link[T] Append, Remove, GetHead, GetTail, Size
TreeNode[T] Convert2Tree(list, root), PrintTree(tree, indent)
Value Valid, Cover, String, Int, Int64, Float64, Bool
Args Put, Get, ArgsRange
Set[T] Add, Has, Remove, Clear, Len, Range, ToSlice
Collect Put, Get

Documentation

Index

Constants

View Source
const (
	TimeLayout = "2006-01-02 15:04:05"
	DateLayout = "2006-01-02"
)

Variables

This section is empty.

Functions

func Any2String added in v1.25.6

func Any2String(v any) string

Any2String 将任意值格式化为字符串

func ArgsRange added in v1.25.5

func ArgsRange(args Args, handle func(k string, v Value))

ArgsRange 遍历参数收集器

func Bool2String added in v1.25.6

func Bool2String(b bool) string

Bool2String 将布尔值格式化为字符串

func Date2String added in v1.25.6

func Date2String(t time.Time) string

func Float642String added in v1.25.6

func Float642String(f float64) string

Float642String 将浮点数值格式化为字符串

func Int2String added in v1.25.6

func Int2String(i int) string

Int2String 将整数值格式化为字符串

func Int642String added in v1.25.6

func Int642String(i int64) string

Int642String 将整数值格式化为字符串

func PrintTree added in v1.25.6

func PrintTree[T any](tree []*TreeNode[T], indent string)

PrintTree 打印树形结构

func String2Bool added in v1.25.6

func String2Bool(s string) bool

String2Bool 将字符串解析为布尔值

func String2Date added in v1.25.6

func String2Date(s string) time.Time

String2Date 将字符串解析为日期值

func String2Float64 added in v1.25.6

func String2Float64(s string) float64

String2Float64 将字符串解析为浮点数值

func String2Int added in v1.25.6

func String2Int(s string) int

String2Int 将字符串解析为整数值

func String2Int64 added in v1.25.6

func String2Int64(s string) int64

String2Int64 将字符串解析为整数值

func String2Time added in v1.25.6

func String2Time(s string) time.Time

String2Time 将字符串解析为时间值

func Time2String added in v1.25.6

func Time2String(t time.Time) string

Time2String 将时间值格式化为字符串

Types

type Args added in v1.25.5

type Args map[string]Value

Args 参数收集器,隐式实现了 CollectValue 可被json序列化,但是不可被json反序列化,

func (Args) Get added in v1.25.5

func (a Args) Get(k string) Value

func (Args) Put added in v1.25.5

func (a Args) Put(k string, v Value)

func (Args) UnmarshalJSON added in v1.25.5

func (a Args) UnmarshalJSON(data []byte) error

type Bool

type Bool struct {
	// contains filtered or unexported fields
}

Bool 布尔值

func NewBool

func NewBool(v ...bool) *Bool

NewBool 创建布尔值

func (*Bool) Bool

func (x *Bool) Bool(def ...bool) bool

func (*Bool) Cover added in v1.25.5

func (x *Bool) Cover(v any)

func (*Bool) Float64

func (x *Bool) Float64(def ...float64) float64

func (*Bool) Int

func (x *Bool) Int(def ...int) int

func (*Bool) Int64

func (x *Bool) Int64(def ...int64) int64

func (*Bool) MarshalJSON

func (x *Bool) MarshalJSON() ([]byte, error)

func (*Bool) String

func (x *Bool) String(def ...string) string

func (*Bool) UnmarshalJSON

func (x *Bool) UnmarshalJSON(bytes []byte) error

func (*Bool) Valid

func (x *Bool) Valid() bool

func (*Bool) Value

func (x *Bool) Value(def ...bool) bool

type Collect added in v1.25.5

type Collect[K comparable, V any] interface {
	Put(k K, v V) // 放入值
	Get(k K) V    // 获取值
}

type CollectAny added in v1.25.5

type CollectAny Collect[string, any] // 任意类型收集器

type CollectString added in v1.25.5

type CollectString Collect[string, string] // 字符串收集器

type CollectValue added in v1.25.5

type CollectValue Collect[string, Value] // 值收集器

type Date

type Date struct {
	Time
}

func NewDate

func NewDate(v ...time.Time) *Date

NewDate 创建日期值

func (*Date) MarshalJSON

func (x *Date) MarshalJSON() ([]byte, error)

func (*Date) UnmarshalJSON

func (x *Date) UnmarshalJSON(bytes []byte) error

type Enum

type Enum[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Enum 枚举类,实现了Collect[K, V]接口

func NewEnum

func NewEnum[K comparable, V any]() *Enum[K, V]

NewEnum key为comparable类型,value为任意类型

func NewStringEnum

func NewStringEnum[V any]() *Enum[string, V]

NewStringEnum key为string类型,value为任意类型

func (*Enum[K, V]) Add

func (e *Enum[K, V]) Add(k K, v V) *Enum[K, V]

Add 添加枚举值

func (*Enum[K, V]) Clear

func (e *Enum[K, V]) Clear()

Clear 清空枚举值

func (*Enum[K, V]) Find added in v1.26.4

func (e *Enum[K, V]) Find(k K) (V, bool)

Find 判断枚举值是否存在

func (*Enum[K, V]) Get

func (e *Enum[K, V]) Get(k K) V

Get 获取枚举值

func (*Enum[K, V]) Keys

func (e *Enum[K, V]) Keys() []K

Keys 返回枚举值的键列表

func (*Enum[K, V]) Len

func (e *Enum[K, V]) Len() int

Len 返回枚举值数量

func (*Enum[K, V]) Put added in v1.25.5

func (e *Enum[K, V]) Put(k K, v V)

Put 添加枚举值

func (*Enum[K, V]) Range added in v1.25.2

func (e *Enum[K, V]) Range(handle func(k K, v V) bool)

Range 遍历枚举值,handle 返回 false 停止遍历

func (*Enum[K, V]) RangeWithIndex added in v1.25.2

func (e *Enum[K, V]) RangeWithIndex(handle func(i int, k K, v V) bool)

RangeWithIndex 遍历枚举值,包含下标

func (*Enum[K, V]) Remove

func (e *Enum[K, V]) Remove(k K)

Remove 删除枚举值

func (*Enum[K, V]) Values

func (e *Enum[K, V]) Values() []V

Values 返回枚举值的值列表

type Float64

type Float64 struct {
	// contains filtered or unexported fields
}

Float64 浮点数值

func NewFloat64

func NewFloat64(f ...float64) *Float64

NewFloat64 创建浮点数值

func (*Float64) Bool

func (x *Float64) Bool(def ...bool) bool

func (*Float64) Cover added in v1.25.5

func (x *Float64) Cover(v any)

func (*Float64) Float64

func (x *Float64) Float64(def ...float64) float64

func (*Float64) Int

func (x *Float64) Int(def ...int) int

func (*Float64) Int64

func (x *Float64) Int64(def ...int64) int64

func (*Float64) MarshalJSON

func (x *Float64) MarshalJSON() ([]byte, error)

func (*Float64) String

func (x *Float64) String(def ...string) string

func (*Float64) UnmarshalJSON

func (x *Float64) UnmarshalJSON(bytes []byte) error

func (*Float64) Valid

func (x *Float64) Valid() bool

func (*Float64) Value

func (x *Float64) Value(def ...float64) float64

type Int

type Int struct {
	// contains filtered or unexported fields
}

Int 整数值

func NewInt

func NewInt(v ...int) *Int

NewInt 创建整数值

func (*Int) Bool

func (x *Int) Bool(def ...bool) bool

func (*Int) Cover added in v1.25.5

func (x *Int) Cover(v any)

func (*Int) Float64

func (x *Int) Float64(def ...float64) float64

func (*Int) Int

func (x *Int) Int(def ...int) int

func (*Int) Int64

func (x *Int) Int64(def ...int64) int64

func (*Int) MarshalJSON

func (x *Int) MarshalJSON() ([]byte, error)

func (*Int) String

func (x *Int) String(def ...string) string

func (*Int) UnmarshalJSON

func (x *Int) UnmarshalJSON(bytes []byte) error

func (*Int) Valid

func (x *Int) Valid() bool

func (*Int) Value

func (x *Int) Value(def ...int) int

type Int64

type Int64 struct {
	// contains filtered or unexported fields
}

Int64 整数值

func NewInt64

func NewInt64(v ...int64) *Int64

NewInt64 创建整数值

func (*Int64) Bool

func (x *Int64) Bool(def ...bool) bool

func (*Int64) Cover added in v1.25.5

func (x *Int64) Cover(v any)

func (*Int64) Float64

func (x *Int64) Float64(def ...float64) float64

func (*Int64) Int

func (x *Int64) Int(def ...int) int

func (*Int64) Int64

func (x *Int64) Int64(def ...int64) int64

func (*Int64) MarshalJSON

func (x *Int64) MarshalJSON() ([]byte, error)

func (*Int64) String

func (x *Int64) String(def ...string) string

func (*Int64) UnmarshalJSON

func (x *Int64) UnmarshalJSON(bytes []byte) error

func (*Int64) Valid

func (x *Int64) Valid() bool

func (*Int64) Value

func (x *Int64) Value(def ...int64) int64

type JSON added in v1.25.6

type JSON interface {
	MarshalJSON() ([]byte, error)
	UnmarshalJSON([]byte) error
}

JSON JSON类型

type Link[T any] struct {
	// contains filtered or unexported fields
}
func NewLink[T any](value T) *Link[T]

NewLink 创建链表

func (*Link[T]) Append added in v1.25.3

func (list *Link[T]) Append(value T) *Link[T]

Append 追加节点,每次追加一个节点

func (*Link[T]) GetHead added in v1.25.3

func (list *Link[T]) GetHead() (T, bool)

GetHead 获取头节点数据

func (*Link[T]) GetTail added in v1.25.3

func (list *Link[T]) GetTail() (T, bool)

GetTail 获取尾节点数据

func (*Link[T]) Remove added in v1.25.3

func (list *Link[T]) Remove() *Link[T]

Remove 删除尾节点,每次删除一个节点,若链表为空则不操作

func (*Link[T]) Size added in v1.25.3

func (list *Link[T]) Size() int

type Set added in v1.26.4

type Set[T comparable] struct {
	// contains filtered or unexported fields
}

Set 泛型集合,并发安全

func NewSet added in v1.26.4

func NewSet[T comparable]() *Set[T]

NewSet 创建泛型集合

func (*Set[T]) Add added in v1.26.4

func (s *Set[T]) Add(v T)

Add 添加元素

func (*Set[T]) Clear added in v1.26.4

func (s *Set[T]) Clear()

Clear 清空集合

func (*Set[T]) Has added in v1.26.4

func (s *Set[T]) Has(v T) bool

Has 判断元素是否存在

func (*Set[T]) Len added in v1.26.4

func (s *Set[T]) Len() int

Len 返回元素数量

func (*Set[T]) Range added in v1.26.4

func (s *Set[T]) Range(handle func(v T) bool)

Range 遍历集合,handle 返回 false 停止遍历

func (*Set[T]) Remove added in v1.26.4

func (s *Set[T]) Remove(v T)

Remove 删除元素

func (*Set[T]) ToSlice added in v1.26.4

func (s *Set[T]) ToSlice() []T

ToSlice 转为切片

type String

type String struct {
	// contains filtered or unexported fields
}

String 字符串值

func NewString

func NewString(v ...string) *String

NewString 创建字符串值

func (*String) Bool

func (x *String) Bool(def ...bool) bool

func (*String) Cover added in v1.25.5

func (x *String) Cover(v any)

func (*String) Float64

func (x *String) Float64(def ...float64) float64

func (*String) Int

func (x *String) Int(def ...int) int

func (*String) Int64

func (x *String) Int64(def ...int64) int64

func (*String) MarshalJSON

func (x *String) MarshalJSON() ([]byte, error)

func (*String) String

func (x *String) String(def ...string) string

func (*String) UnmarshalJSON

func (x *String) UnmarshalJSON(bytes []byte) error

func (*String) Valid

func (x *String) Valid() bool

func (*String) Value

func (x *String) Value(def ...string) string

type Time

type Time struct {
	// contains filtered or unexported fields
}

func NewTime

func NewTime(v ...time.Time) *Time

NewTime 创建时间值

func (*Time) Bool added in v1.25.6

func (x *Time) Bool(def ...bool) bool

func (*Time) Cover added in v1.25.6

func (x *Time) Cover(v any)

func (*Time) Float64 added in v1.25.6

func (x *Time) Float64(def ...float64) float64

func (*Time) Int added in v1.25.6

func (x *Time) Int(def ...int) int

func (*Time) Int64 added in v1.25.6

func (x *Time) Int64(def ...int64) int64

func (*Time) MarshalJSON

func (x *Time) MarshalJSON() ([]byte, error)

func (*Time) String added in v1.25.6

func (x *Time) String(def ...string) string

func (*Time) UnmarshalJSON

func (x *Time) UnmarshalJSON(bytes []byte) error

func (*Time) Valid

func (x *Time) Valid() bool

func (*Time) Value

func (x *Time) Value(def ...time.Time) time.Time

type TreeNode

type TreeNode[T any] struct {
	Id       string         `json:"id"`
	Pid      string         `json:"pid"`
	Depth    int            `json:"depth"`
	Data     T              `json:"data"`
	Children []*TreeNode[T] `json:"children"`
}

TreeNode 树形节点

func Convert2Tree

func Convert2Tree[N treeNode](list []N, root string) []*TreeNode[N]

Convert2Tree 平铺数组转为树形结构

type Value

type Value interface {
	Valid() bool                    // 是否有效
	Cover(v any)                    // 覆盖值
	String(def ...string) string    // 转为字符串,若无效则返回默认值
	Int(def ...int) int             // 转为整数,若无效则返回默认值
	Int64(def ...int64) int64       // 转为整数,若无效则返回默认值
	Float64(def ...float64) float64 // 转为浮点数,若无效则返回默认值
	Bool(def ...bool) bool          // 转为布尔值,若无效则返回默认值
}

Value 任意值

func NewValue

func NewValue(v any) Value

NewValue 创建任意值

type Zero

type Zero struct{}

Zero 零值

func NewZero added in v1.25.4

func NewZero() *Zero

NewZero 创建零值

func (*Zero) Bool

func (z *Zero) Bool(...bool) bool

func (*Zero) Cover added in v1.25.5

func (z *Zero) Cover(_ any)

func (*Zero) Float64

func (z *Zero) Float64(...float64) float64

func (*Zero) Int

func (z *Zero) Int(...int) int

func (*Zero) Int64

func (z *Zero) Int64(...int64) int64

func (*Zero) MarshalJSON added in v1.25.5

func (z *Zero) MarshalJSON() ([]byte, error)

func (*Zero) String

func (z *Zero) String(...string) string

func (*Zero) UnmarshalJSON added in v1.25.5

func (z *Zero) UnmarshalJSON(_ []byte) error

func (*Zero) Valid

func (z *Zero) Valid() bool

Jump to

Keyboard shortcuts

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