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的使用方式,不足之处希望能多多提意见

------结束

相关推荐
ifanatic1 小时前
[面试]-golang基础面试题总结
面试·职场和发展·golang
懒是一种态度1 小时前
Golang 调用 mongodb 的函数
数据库·mongodb·golang
XINGTECODE2 小时前
海盗王集成网关和商城服务端功能golang版
开发语言·后端·golang
入 梦皆星河2 小时前
在 Ubuntu/Debian 上安装 Go
ubuntu·golang·debian
凡人的AI工具箱2 小时前
15分钟学 Go 第 60 天 :综合项目展示 - 构建微服务电商平台(完整示例25000字)
开发语言·后端·微服务·架构·golang
007php00716 小时前
GoZero 上传文件File到阿里云 OSS 报错及优化方案
服务器·开发语言·数据库·python·阿里云·架构·golang
高 朗17 小时前
【GO基础学习】基础语法(2)切片slice
开发语言·学习·golang·slice
IT书架18 小时前
golang面试题
开发语言·后端·golang
醒过来摸鱼1 天前
【Golang】协程
开发语言·后端·golang
灼华十一1 天前
算法编程题-排序
数据结构·算法·golang·排序算法