golang Copier 数据复制

Copier

I am a copier, I copy everything from one to another

Copier是golang实现的,实现不同数据结构之间数据复制的工具包

github地址

使用方法

以User和Employee之间相互复制为例

使用的版本为 v0.3.5

入门

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

type User struct {
	Name   string
	Age    int32
	Salary int
}

type Employee struct {
	Name   string
	Age    int32
	Salary int
}

func main() {
	user := User{
		Name:   "Jinzhu",
		Age:    18,
		Salary: 200000,
	}
	var employee = Employee{}

	// 从user把数据复制到employee中
	err := copier.Copy(&employee, user)

	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", employee)
	}
}

// main.Employee{Name:"Jinzhu", Age:18, Salary:200000}

toValue 传参必须为指针

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

type User struct {
	Name   string
	Age    int32
	Salary int
}

type Employee struct {
	Name   string
	Age    int32
	Salary int
}

func main() {
	user := User{
		Name:   "Jinzhu",
		Age:    18,
		Salary: 200000,
	}
	employee := Employee{}
	// 正确用法
	// err := copier.Copy(&employee, user)
	err := copier.Copy(employee, user)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", employee)
	}
}

// copy destination is invalid

结构体之间相互复制,默认以字段名作为映射

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

type User struct {
	Name   string
	Age    int32
	Salary int
}

type Employee struct {
	Name   string
	Age    int32
	Salary int
}

func main() {
	user := User{
		Name:   "Jinzhu",
		Age:    18,
		Salary: 200000,
	}
	employee := Employee{}
	err := copier.Copy(&employee, &user)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", employee)
	}
}
// 结果:main.Employee{Name:"Jinzhu", Age:18, Salary:200000}

如果字段名不相同,则不会进行字段值复制,但是不会影响其他字段值复制

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

type User struct {
	Name   string
	Age    int32
	Salary int
}

type Employee struct {
	Title  string
	Age    int32
	Salary int
}

func main() {
	user := User{
		Name:   "Jinzhu",
		Age:    18,
		Salary: 200000,
	}
	employee := Employee{}
	err := copier.Copy(&employee, &user)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", employee)
	}
}

// 结果:main.Employee{Title:"", Age:18, Salary:200000}

如果字段名不相同的字段值想进行复制,可以通过标签进行映射

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

type User struct {
	Name   string
	Age    int32
	Salary int
}

type Employee struct {
	Title  string `copier:"Name"`
	Age    int32
	Salary int
}

func main() {
	user := User{
		Name:   "Jinzhu",
		Age:    18,
		Salary: 200000,
	}
	employee := Employee{}
	err := copier.Copy(&employee, &user)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", employee)
	}
}

// 结果:main.Employee{Title:"Jinzhu", Age:18, Salary:200000}

copier 标签字段名必须是首字母大写

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

type User struct {
	Name   string
	Age    int32
	Salary int
}

type Employee struct {
	Title  string `copier:"name"`
	Age    int32
	Salary int
}

func main() {
	user := User{
		Name:   "Jinzhu",
		Age:    18,
		Salary: 200000,
	}
	employee := Employee{}
	err := copier.Copy(&employee, &user)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", employee)
	}
}

// copier field name tag must be start upper case

相互映射的字段,数据类型要尽量相同,否则会出现意想不到的结果

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

type User struct {
	Name   string
	Age    int32
	Salary int
}

type Employee struct {
	Title  int `copier:"Name"`
	Age    string
	Salary int
}

func main() {
	user := User{
		Name:   "Jinzhu",
		Age:    18,
		Salary: 200000,
	}
	employee := Employee{}
	err := copier.Copy(&employee, &user)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", employee)
	}
}

// main.Employee{Title:0, Age:"\x12", Salary:200000}

支持通过同样的名字实现method给field赋值

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

type User struct {
	Name   string
	Age    int32
	Salary int
}

func (receiver User) Title() string {
	return "Golang " + receiver.Name
}

type Employee struct {
	Title  string
	Age    int32
	Salary int
}

func main() {
	user := User{
		Name:   "Jinzhu",
		Age:    18,
		Salary: 200000,
	}
	employee := Employee{}
	err := copier.Copy(&employee, &user)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", employee)
	}
}

// User.Title() 给 Employee.Title 赋值
// main.Employee{Title:"Golang Jinzhu", Age:18, Salary:200000}

支持通过同样的名字实现field给method赋值

method必须有唯一的形参,形参的数据类型跟field要一致

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

type User struct {
	Name   string
	Age    int32
	Salary int
}

type Employee struct {
	Title  string
	Age    int32
	Salary int
}

// 复制失败
//func (receiver *Employee) Name(name string, age int) {
//	receiver.Title = "Title " + name
//}

// 复制失败
//func (receiver *Employee) Name() {
//	receiver.Title = "Title " + name
//}

func (receiver *Employee) Name(name string) {
	receiver.Title = "Title " + name
}

func main() {
	user := User{
		Name:   "Jinzhu",
		Age:    18,
		Salary: 200000,
	}
	employee := Employee{}
	err := copier.Copy(&employee, &user)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", employee)
	}
}

// main.Employee{Title:"Title Jinzhu", Age:18, Salary:200000}

must 标签

must 标签用来指定toValue.field 必须有相应的 fromValue.field ,否则会报错

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

type User struct {
	Name   string
	Age    int32
	Salary int
}

type Employee struct {
	Title  string `copier:"must"`
	Age    int32
	Salary int
}

func main() {
	user := User{
		Name:   "Jinzhu",
		Age:    18,
		Salary: 200000,
	}
	employee := Employee{}
	err := copier.Copy(&employee, &user)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", employee)
	}
}

// panic: Field Title has must tag but was not copied

忽略指定字段

通过标签 copier:"-"来标识字段要跳过字段值复制,而且只有标识在toValue字段上才会生效

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

type User struct {
	Name   string
	Age    int32
	Salary int
}

type Employee struct {
	Name   string `copier:"-"`
	Age    int32
	Salary int
}

func main() {
	user := User{
		Name:   "Jinzhu",
		Age:    18,
		Salary: 200000,
	}
	employee := Employee{}
	err := copier.Copy(&employee, &user)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", employee)
	}
}

// main.Employee{Name:"", Age:18, Salary:200000}

nopanic 标签

nopanic 用来告诉copier ,指定字段出现异常,通过返回error方式报错,而不是通过panic方式报错

当前的版本,源代码在返回error后,并没有对外抛出,所以当前的效果是,不抛panic,也不返回error

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

type User struct {
	Name   string
	Age    int32
	Salary int
}

type Employee struct {
	Title  string `copier:"must,nopanic"`
	Age    int32
	Salary int
}

func main() {
	user := User{
		Name:   "Jinzhu",
		Age:    18,
		Salary: 200000,
	}
	employee := Employee{}
	err := copier.Copy(&employee, &user)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", employee)
	}
}

// main.Employee{Title:"", Age:18, Salary:200000}

结构体批量复制

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

type User struct {
	Name   string
	Age    int32
	Salary int
}

type Employee struct {
	Name   string
	Age    int32
	Salary int
}

func main() {
	users := []User{
		{
			Name:   "Jinzhu",
			Age:    18,
			Salary: 200000,
		},
		{
			Name:   "Jinzhu1",
			Age:    20,
			Salary: 180000,
		},
	}
	var employee []Employee
	err := copier.Copy(&employee, users)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", employee)
	}
}

// []main.Employee{main.Employee{Name:"Jinzhu", Age:18, Salary:200000}, main.Employee{Name:"Jinzhu1", Age:20, Salary:180000}}

结构体复制到结构体列表

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

type User struct {
	Name   string
	Age    int32
	Salary int
}

type Employee struct {
	Name   string
	Age    int32
	Salary int
}

func main() {
	users := User{
		Name:   "Jinzhu",
		Age:    18,
		Salary: 200000,
	}
	var employee []Employee
	err := copier.Copy(&employee, users)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", employee)
	}
}

// []main.Employee{main.Employee{Name:"Jinzhu", Age:18, Salary:200000}}

map To map 复制

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

func main() {
	user := map[string]interface{}{
		"name":   "Jinzhu",
		"age":    18,
		"salary": 200000,
	}
	var employee = map[string]interface{}{}
	err := copier.Copy(&employee, user)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", employee)
	}
}

// map[string]interface {}{"age":18, "name":"Jinzhu", "salary":200000}

CopyWithOption 使用

CopyWithOption 支持调用时传参选择项,来影响copier的行为

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

type User struct {
	Name   string
	Age    int32
	Salary int
}

type Employee struct {
	Name   string
	Age    int32
	Salary int
}

func main() {
	user := User{
		Name:   "Jinzhu",
		Age:    18,
		Salary: 200000,
	}
	var employee = Employee{
		Name: "Jinzhu-Name",
	}
	err := copier.CopyWithOption(&employee, user, copier.Option{})
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", employee)
	}
}

// main.Employee{Name:"Jinzhu", Age:18, Salary:200000}
IgnoreEmpty选项

IgnoreEmpty 选项用来指定是否跳过空值

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

type User struct {
	Name   string
	Age    int32
	Salary int
}

type Employee struct {
	Name   string
	Age    int32
	Salary int
}

func main() {
	user := User{
		Name:   "",
		Age:    18,
		Salary: 200000,
	}
	var employee = Employee{
		Name: "Jinzhu-Name",
	}
	err := copier.CopyWithOption(&employee, user, copier.Option{IgnoreEmpty: true})
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", employee)
	}
}

// main.Employee{Name:"Jinzhu-Name", Age:18, Salary:200000}
Converters 选项

Converters 选项用来自定义转换方式

go 复制代码
package main

import (
	"fmt"
	"github.com/jinzhu/copier"
	"time"
)

type User struct {
	Name     string
	Age      int32
	Salary   int
	Birthday time.Time
}

type Employee struct {
	Name     string
	Age      int32
	Salary   int
	Birthday string
}

func main() {
	user := User{
		Name:     "Jinzhu",
		Age:      18,
		Salary:   200000,
		Birthday: time.Now(),
	}
	var employee = Employee{
		Name: "Jinzhu-Name",
	}
	err := copier.CopyWithOption(&employee, user, copier.Option{IgnoreEmpty: true, Converters: []copier.TypeConverter{
		{
			SrcType: time.Time{},
			DstType: "",
			Fn: func(src interface{}) (interface{}, error) {
				srcTime, ok := src.(time.Time)
				if !ok {
					return "", nil
				}
				return srcTime.Format("2006-01-02 15:04:05"), nil
			},
		},
	}})

	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%#v \n", user)
		fmt.Printf("%#v \n", employee)
	}
}

// main.User{Name:"Jinzhu", Age:18, Salary:200000, Birthday:time.Date(2023, time.November, 12, 20, 48, 47, 73860000, time.Local)}
// main.Employee{Name:"Jinzhu", Age:18, Salary:200000, Birthday:"2023-11-12 20:48:47"}
DeepCopy 选项
待补充

总结

整体来说,copier能满足我们日常业务开发中的大部分场景,而且可以有效的解耦数据结构之间的依赖,通过一种低耦合的方式,实现数据复制任务

附:本文只是简单总结了copier的使用方式,不足之处希望能多多提意见

------结束

相关推荐
007php0073 小时前
Go语言zero项目部署后启动失败问题分析与解决
java·服务器·网络·python·golang·php·ai编程
MClink9 小时前
Go怎么做性能优化工具篇之pprof
开发语言·性能优化·golang
m0_7482546612 小时前
go官方日志库带色彩格式化
android·开发语言·golang
Algorithm157615 小时前
云原生相关的 Go 语言工程师技术路线(含博客网址导航)
开发语言·云原生·golang
Narutolxy16 小时前
深入探讨 Go 中的高级表单验证与翻译:Gin 与 Validator 的实践之道20241223
开发语言·golang·gin
Hello.Reader16 小时前
全面解析 Golang Gin 框架
开发语言·golang·gin
hkNaruto2 天前
【P2P】【Go】采用go语言实现udp hole punching 打洞 传输速度测试 ping测试
golang·udp·p2p
入 梦皆星河2 天前
go中常用的处理json的库
golang
海绵波波1072 天前
Gin-vue-admin(2):项目初始化
vue.js·golang·gin
每天写点bug2 天前
【go每日一题】:并发任务调度器
开发语言·后端·golang