Go Copier库

3 min

:white_circle:copier库

copier 是一个用于 Go 语言的库,可以方便地将一个结构体的字段复制到另一个结构体。它支持深拷贝、字段转换、类型转换等功能。以下是一些必须掌握的基本用法:

1. 简单拷贝结构体

使用 copier.Copy 方法可以将一个结构体的字段值复制到另一个结构体中。源结构体和目标结构体的字段名必须匹配,且字段类型要兼容。

import "github.com/jinzhu/copier"

type Source struct {
    Name string
    Age  int
}

type Destination struct {
    Name string
    Age  int
}

src := Source{Name: "John", Age: 30}
var dest Destination
copier.Copy(&dest, &src)

2. 深拷贝(Deep Copy)

默认情况下,copier 进行的是浅拷贝。如果需要深拷贝(即复制引用类型的值,而不是它们的引用),可以使用 copier.CopyWithOption 并设置 DeepCopy: true

src := Source{Name: "John", Age: 30}
var dest Destination
copier.CopyWithOption(&dest, &src, copier.Option{DeepCopy: true})

3. 忽略空值(OmitEmpty

copier 允许忽略源结构体中空值的字段,使用 OmitEmpty: true 选项。

src := Source{Name: "", Age: 30}
var dest Destination
copier.CopyWithOption(&dest, &src, copier.Option{OmitEmpty: true})

4. 字段转换(Field Translation)

当源和目标结构体的字段名称不完全匹配时,可以通过结构体标签 copier 来指定映射关系。

type Source struct {
    FirstName string
}

type Destination struct {
    Name string `copier:"FirstName"`
}

src := Source{FirstName: "John"}
var dest Destination
copier.Copy(&dest, &src)

5. 类型转换

如果源字段和目标字段类型不同,但可以通过类型转换完成复制,copier 会尝试进行转换。

type Source struct {
    Age int
}

type Destination struct {
    Age string
}

src := Source{Age: 30}
var dest Destination
copier.Copy(&dest, &src)

6. 复制切片(Slices)

copier 也支持复制切片,源和目标的切片类型可以不同,但必须可转换。

type Source struct {
    Age int
}

type Destination struct {
    Age int
}

srcSlice := []Source{{Age: 20}, {Age: 30}}
var destSlice []Destination
copier.Copy(&destSlice, &srcSlice)

7. 复制嵌套结构体

copier 支持嵌套结构体的复制,可以深度复制嵌套的字段。

type Address struct {
    City string
}

type Source struct {
    Name    string
    Address Address
}

type Destination struct {
    Name    string
    Address Address
}

src := Source{Name: "John", Address: Address{City: "New York"}}
var dest Destination
copier.Copy(&dest, &src)