golang Copier 数据复制

Copier

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

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

github地址

使用方法

以User和Employee之间相互复制为例
使用的版本为 v0.3.5

入门

package mainimport ("fmt""github.com/jinzhu/copier"
)type User struct {Name   stringAge    int32Salary int
}type Employee struct {Name   stringAge    int32Salary 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 传参必须为指针

package mainimport ("fmt""github.com/jinzhu/copier"
)type User struct {Name   stringAge    int32Salary int
}type Employee struct {Name   stringAge    int32Salary 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

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

package mainimport ("fmt""github.com/jinzhu/copier"
)type User struct {Name   stringAge    int32Salary int
}type Employee struct {Name   stringAge    int32Salary 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}

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

package mainimport ("fmt""github.com/jinzhu/copier"
)type User struct {Name   stringAge    int32Salary int
}type Employee struct {Title  stringAge    int32Salary 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}

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

package mainimport ("fmt""github.com/jinzhu/copier"
)type User struct {Name   stringAge    int32Salary int
}type Employee struct {Title  string `copier:"Name"`Age    int32Salary 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 标签字段名必须是首字母大写

package mainimport ("fmt""github.com/jinzhu/copier"
)type User struct {Name   stringAge    int32Salary int
}type Employee struct {Title  string `copier:"name"`Age    int32Salary 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

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

package mainimport ("fmt""github.com/jinzhu/copier"
)type User struct {Name   stringAge    int32Salary int
}type Employee struct {Title  int `copier:"Name"`Age    stringSalary 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赋值

package mainimport ("fmt""github.com/jinzhu/copier"
)type User struct {Name   stringAge    int32Salary int
}func (receiver User) Title() string {return "Golang " + receiver.Name
}type Employee struct {Title  stringAge    int32Salary 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要一致

package mainimport ("fmt""github.com/jinzhu/copier"
)type User struct {Name   stringAge    int32Salary int
}type Employee struct {Title  stringAge    int32Salary 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 ,否则会报错

package mainimport ("fmt""github.com/jinzhu/copier"
)type User struct {Name   stringAge    int32Salary int
}type Employee struct {Title  string `copier:"must"`Age    int32Salary 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字段上才会生效

package mainimport ("fmt""github.com/jinzhu/copier"
)type User struct {Name   stringAge    int32Salary int
}type Employee struct {Name   string `copier:"-"`Age    int32Salary 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
在这里插入图片描述

在这里插入图片描述

package mainimport ("fmt""github.com/jinzhu/copier"
)type User struct {Name   stringAge    int32Salary int
}type Employee struct {Title  string `copier:"must,nopanic"`Age    int32Salary 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}

结构体批量复制

package mainimport ("fmt""github.com/jinzhu/copier"
)type User struct {Name   stringAge    int32Salary int
}type Employee struct {Name   stringAge    int32Salary int
}func main() {users := []User{{Name:   "Jinzhu",Age:    18,Salary: 200000,},{Name:   "Jinzhu1",Age:    20,Salary: 180000,},}var employee []Employeeerr := 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}}

结构体复制到结构体列表

package mainimport ("fmt""github.com/jinzhu/copier"
)type User struct {Name   stringAge    int32Salary int
}type Employee struct {Name   stringAge    int32Salary int
}func main() {users := User{Name:   "Jinzhu",Age:    18,Salary: 200000,}var employee []Employeeerr := 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 复制


package mainimport ("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的行为

package mainimport ("fmt""github.com/jinzhu/copier"
)type User struct {Name   stringAge    int32Salary int
}type Employee struct {Name   stringAge    int32Salary 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 选项用来指定是否跳过空值

package mainimport ("fmt""github.com/jinzhu/copier"
)type User struct {Name   stringAge    int32Salary int
}type Employee struct {Name   stringAge    int32Salary 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 选项用来自定义转换方式

package mainimport ("fmt""github.com/jinzhu/copier""time"
)type User struct {Name     stringAge      int32Salary   intBirthday time.Time
}type Employee struct {Name     stringAge      int32Salary   intBirthday 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的使用方式,不足之处希望能多多提意见

——结束

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/169999.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

头歌答案--爬虫实战

目录 urllib 爬虫 第1关:urllib基础 任务描述 第2关:urllib进阶 任务描述 requests 爬虫 第1关:requests 基础 任务描述 第2关:requests 进阶 任务描述 网页数据解析 第1关:XPath解析网页 任务描述 第…

hive和spark-sql中 日期和时间相关函数 测试对比

测试版本: hive 2.3.4 spark 3.1.1 hadoop 2.7.7 1、增加月份 add_months(timestamp date, int months)add_months(timestamp date, bigint months)Return type: timestampusage:add_months(now(),1) 2、增加日期 adddate(timestamp startdate, int days)…

【Redis系列】Redis的核心命令(上)

哈喽,大家好,我是小浪。那么上篇博客教会了大家如何在Linux上安装Redis,那么本篇博客就要正式开始学习Redis啦,跟着俺的随笔往下看~ 1、启动Redis 那么如何启动Redis呢?最常用的是以下这个命令: redis-cl…

【阿里云】函数计算 X 通义千问快速部署

写在前面:博主是一只经过实战开发历练后投身培训事业的“小山猪”,昵称取自动画片《狮子王》中的“彭彭”,总是以乐观、积极的心态对待周边的事物。本人的技术路线从Java全栈工程师一路奔向大数据开发、数据挖掘领域,如今终有小成…

【Android】Android apk 逆向编译

链接:https://pan.baidu.com/s/14r5s9EJwQgeLK5cCb1Gq1Q 提取码:qdqt 解压jadx 在 lib 文件内找到 jadx-gui-1.4.7.jar 打开cmd 执行 :java -jar jadx-gui-1.4.7.jar示列:

生成式AI - Knowledge Graph Prompting:一种基于大模型的多文档问答方法

大型语言模型(LLM)已经彻底改变了自然语言处理(NLP)任务。它们改变了我们与文本数据交互和处理的方式。这些强大的AI模型,如OpenAI的GPT-4,改变了理解、生成人类类似文本的方式,导致各种行业出现…

[.NET]启明星电子文档管理系统edoc v33.0

启明星电子文档库是一个简单、实用的企业文档在线存储工具。系统采用ASP.NETMSSQL2008 Express开发,所有文档数据都以二进制方式存储在数据库里方便备份。 系统的特点包括: (1)支持文档在线预览,可以在线预览word&…

【2011年数据结构真题】

41题 41题解答: (1)图 G 的邻接矩阵 A 如下所示: 由题意得,A为上三角矩阵,在上三角矩阵A[6][6]中,第1行至第5行主对角线上方的元素个数分别为5, 4, 3, 2, 1 用 “ 平移” 的思想,…

Halcon WPF 开发学习笔记(4):Halcon 锚点坐标打印

文章目录 专栏前言锚点二次开发添加回调函数辅助Model类 下集预告 专栏 Halcon开发 博客专栏 WPF/HALCON机器视觉合集 前言 Halcon控件C#开发是我们必须掌握的,因为只是单纯的引用脚本灵活性过低,我们要拥有Halcon辅助开发的能力 锚点开发是我们常用的…

SolidWorks绘制花瓶教程

这个花瓶是我学习solidworks画图以来用时最长的一个图形了,特此记录一下,用了我足足两个早晨才把他给画出来,我这是跟着哔站里的隔壁老王学习的,下面是视频地址:点击我一下看视频教程 下面是我的绘图过程,…

Anolis 8.6 安装 Drawio

Anolis 8.6 安装 Drawio 22.1.0 一.RPM版(不建议)二.WAR 包部署 一.RPM版(不建议) Draw RPM 包下载链接 RPM 包直接基于Linux图形化能力部署,服务器类型的Linux系统启动RPM包安装的Draw可能比较复杂 系统版本 ## 1.…

分类预测 | Matlab实现PSO-BiLSTM粒子群算法优化双向长短期记忆神经网络的数据多输入分类预测

分类预测 | Matlab实现PSO-BiLSTM粒子群算法优化双向长短期记忆神经网络的数据多输入分类预测 目录 分类预测 | Matlab实现PSO-BiLSTM粒子群算法优化双向长短期记忆神经网络的数据多输入分类预测分类效果基本描述程序设计参考资料 分类效果 基本描述 1.Matlab实现PSO-BiLSTM粒子…