feat: replace mapping generation with checked copy utilities

This commit is contained in:
2026-09-25 17:27:28 +08:00
parent ad9257d202
commit fd83235ce7
45 changed files with 2366 additions and 1872 deletions

61
examples/copying/main.go Normal file
View File

@@ -0,0 +1,61 @@
// copying demonstrates optional Go-to-Go conversion and checked deep copying.
package main
import (
"errors"
"fmt"
"log"
"time"
"git.yuntuo.hk/k2safe/go-omni/copyx"
)
type Input struct {
Name string
Enabled bool
Tags []string
CreatedAt time.Time
}
type View struct {
DisplayName string
Enabled bool
Tags []string
CreatedAt string
}
func run() error {
converter, err := copyx.New(
copyx.WithDeepCopy(),
copyx.WithFieldNames[Input, View](map[string]string{"Name": "DisplayName"}),
copyx.WithConverter(func(v time.Time) (string, error) { return v.UTC().Format(time.RFC3339), nil }),
)
if err != nil {
return err
}
source := Input{Name: "sample", Enabled: false, Tags: []string{"original"}, CreatedAt: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)}
var target View
if err = converter.Copy(&target, source); err != nil {
return err
}
target.Tags[0] = "changed"
fmt.Printf("name=%s enabled=%t time=%s sourceTag=%s\n", target.DisplayName, target.Enabled, target.CreatedAt, source.Tags[0])
cloned, err := copyx.Clone(source)
if err != nil {
return err
}
cloned.Tags[0] = "separate"
fmt.Println("clone detached:", source.Tags[0] == "original")
_, err = copyx.Clone(source.Tags, copyx.WithConverter(func(v []string) ([]string, error) { return v, nil }))
fmt.Println("shared converter rejected:", errors.Is(err, copyx.ErrSharedReference))
if !errors.Is(err, copyx.ErrSharedReference) {
return errors.New("expected alias rejection")
}
return nil
}
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}