structx

package
v0.3.3 Latest Latest
Warning

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

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

README

Structx (结构体扩展)

提供结构体转换与比较工具。

API

StructConvert
  • 签名: func StructConvert[S any, T any](source *S, target *T)
  • 描述: 通过 JSON 序列化/反序列化实现结构体之间的转换。
  • 警告: 性能较低,仅适用于非关键路径。建议高性能场景使用专门的转换库。
DiffStruct
  • 签名: func DiffStruct[O any, N any](old O, new N, ignore []string) map[string]interface{}
  • 描述: 比较两个结构体,返回发生变更的字段名及其新值。支持忽略指定字段。

示例

import (
    "fmt"
    "github.com/fireflycore/go-utils/structx"
)

type User struct {
    Name string
    Age  int
}

func main() {
    // StructConvert
    u1 := User{Name: "Alice", Age: 30}
    var u2 User
    structx.StructConvert(&u1, &u2)
    
    // DiffStruct
    oldUser := User{Name: "Bob", Age: 20}
    newUser := User{Name: "Bob", Age: 21}
    diff := structx.DiffStruct(oldUser, newUser, nil)
    fmt.Println(diff) // map[Age:21]
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DiffStruct

func DiffStruct[O any, N any](old O, new N, ignore []string) map[string]interface{}

DiffStruct 比较两个结构体的字段差异 old: 旧结构体对象(或指针) new: 新结构体对象(或指针) ignore: 需要忽略比较的字段名列表 返回: 变更字段名到新值的映射 (map[string]interface{}) 注意: 仅比较导出字段,且 old/new 必须是相同的结构体类型(或其指针)

func StructConvert

func StructConvert[S any, T any](source *S, target *T) error

StructConvert 结构体转换工具 source: 源结构体指针 target: 目标结构体指针 原理:通过 JSON 序列化 source 再反序列化到 target 警告:性能较差,仅适用于非关键路径或对性能不敏感的场景 建议:高性能场景请使用手动赋值或专门的转换库(如 goverter)

Types

This section is empty.

Jump to

Keyboard shortcuts

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