Skip to content

gocopy is a deep copy tool by reflect, and without third-party dependencies

Notifications You must be signed in to change notification settings

CaiJinKen/gocopy

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 

Repository files navigation

gocopy

NewFrom is a deep copy func by reflect, and wihtout third-party dependencies. Supported types as flow:

  • signed/unsigned int
  • float
  • string
  • bool
  • map
  • slice / array
  • ptr
  • complex
  • struct
  • interface
  • chan
  • func
  • unsafePointer

Note: The func NewFrom returns itself when input is a chan or func or unsafePointer.

Update is a update tool by reflect, assign value from src to dst when src and dst has same field name and data type

Install

go get github.com/CaiJinKen/gocopy

Example

NewFrom:

package main

import (
  "fmt"
  
  "github.com/CaiJinKen/gocopy"
)

type Config struct {
	Id    uint32
	Name  string
	Used  bool
	Pets  []*Dog
	PetMp map[string]*Dog
}

type Dog struct {
	Name string
	Age  uint8
}

func main() {
	conf := Config{
		Id:    10,
		Name:  "tiger",
		Used:  true,
		Pets:  []*Dog{{Name: "k1", Age: 1}, {Name: "k2", Age: 2}},
		PetMp: map[string]*Dog{"v1": {Name: "v1", Age: 3}, "v2": {Name: "v2", Age: 4}},
	}

	data := gocopy.NewFrom(conf) // data=>main.Config
	data = gocopy.NewFrom(&conf) // data=>&main.Config
	// data will intact when conf changed
	
	// handle data
	fmt.Printf("data %v\n",data)
}

Update:

package main

import (
  "fmt"
  
  "github.com/CaiJinKen/gocopy"
)

type Config struct {
	Id    uint32
	Name  string
	Used  bool
	Pets  []*Dog
	PetMp map[string]*Dog
}

type Dog struct {
	Name string
	Age  uint8
}

func main() {
	conf := Config{
		Id:    10,
		Name:  "tiger",
		Used:  true,
		Pets:  []*Dog{{Name: "k1", Age: 1}, {Name: "k2", Age: 2}},
		PetMp: map[string]*Dog{"v1": {Name: "v1", Age: 3}, "v2": {Name: "v2", Age: 4}},
	}
  
  data := &Config

	err := gocopy.Update(conf, data)
	err = gocopy.Update(&conf, data)
	// dst change when conf reference data changed
	
	// handle data
	fmt.Printf("data %v\n",data)
}

About

gocopy is a deep copy tool by reflect, and without third-party dependencies

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages