copier
Repositório: jinzhu/copier: Copier for golang, copy value from struct to struct and more (github.com)
Documentação: jinzhu/copier: Copier for golang, copy value from struct to struct and more (github.com)
copier é uma biblioteca para cópia de tipos em Go, principalmente usada para conversão entre estruturas. O autor é o mesmo do gorm, e possui as seguintes características:
- Cópia profunda
- Copia campos com o mesmo nome
- Copia slices
- Copia maps
- Copia métodos
Como a cópia do copier depende de reflexão, haverá alguma perda de desempenho. Geralmente, bibliotecas de cópia de tipos são divididas em duas categorias: uma baseada em reflexão, como o copier, e outra baseada em geração de código, que gera código de conversão de tipo. Este método não causa perda de desempenho, e bibliotecas similares incluem jmattheis/goverter.
Instalação
go get github.com/jinzhu/copierUso
Esta biblioteca é muito simples de usar, mas extremamente útil. Ela expõe apenas duas funções, uma é copier.Copy.
func Copy(toValue interface{}, fromValue interface{}) (err error)A outra é copier.CopyWithOption, que permite configurações personalizadas para o comportamento de cópia. Por padrão, não realiza cópia profunda.
type Option struct {
IgnoreEmpty bool
CaseSensitive bool
DeepCopy bool
FieldNameMapping []FieldNameMapping
}
func CopyWithOption(toValue interface{}, fromValue interface{}, opt Option) (err error)Abaixo está um exemplo de conversão entre estruturas de tipos diferentes. As estruturas User e Student são tipos completamente diferentes, sem nenhuma relação.
type User struct {
Id string
Name string
// Ignora este campo quando é a estrutura de destino
Address string `copier:"-"`
}
type Student struct {
// Especifica o nome do campo
StudentId string `copier:"Id"`
StudentName string `copier:"Name"`
Address string
School string
Class string
}
func main() {
student := Student{
StudentId: "123",
StudentName: "jack",
Address: "usa",
School: "MIT",
Class: "AI",
}
user := User{}
if err := copier.Copy(&user, &student); err != nil {
panic(err)
}
fmt.Printf("%+v\n", student)
fmt.Printf("%+v\n", user)
}Saída:
{StudentId:123 StudentName:jack Address:usa School:MIT Class:AI}
{Id:123 Name:jack Address:}Abaixo está a cópia de slice:
func main() {
student := []Student{
{
StudentId: "123",
StudentName: "jack",
Address: "usa",
School: "MIT",
Class: "AI",
},
{
StudentId: "123",
StudentName: "jack",
Address: "usa",
School: "MIT",
Class: "AI",
},
}
var user []User
if err := copier.Copy(&user, &student); err != nil {
panic(err)
}
fmt.Printf("%+v\n", student)
fmt.Printf("%+v\n", user)
}Saída:
[{StudentId:123 StudentName:jack Address:usa School:MIT Class:AI} {StudentId:123 StudentName:jack Address:usa School:MIT Class:AI}]
[{Id:123 Name:jack Address:} {Id:123 Name:jack Address:}]Cópia de map:
type User struct {
Id string
Name string
// Ignora este campo quando é a estrutura de destino
Address string `copier:"-"`
}
type Student struct {
// Especifica o nome do campo
StudentId string `copier:"Id"`
StudentName string `copier:"Name"`
Address string
School string
Class string
}
func main() {
student := Student{
StudentId: "123",
StudentName: "jack",
Address: "usa",
School: "MIT",
Class: "AI",
}
src := make(map[string]Student)
src["a"] = student
src["b"] = student
dest := make(map[string]User)
if err := copier.Copy(&dest, &src); err != nil {
panic(err)
}
fmt.Printf("%+v\n", src)
fmt.Printf("%+v\n", dest)
}Saída:
map[a:{StudentId:123 StudentName:jack Address:usa School:MIT Class:AI} b:{StudentId:123 StudentName:jack Address:usa School:MIT Class:AI}]
map[a:{Id:123 Name:jack Address:} b:{Id:123 Name:jack Address:}]Personalização
Também é possível personalizar métodos de conversão, basta passar copier.TypeConverter.
type TypeConverter struct {
SrcType interface{}
DstType interface{}
Fn func(src interface{}) (dst interface{}, err error)
}Como mostrado abaixo:
type User struct {
Id string
Name string
// Ignora este campo quando é a estrutura de destino
Address string `copier:"-"`
}
type Student struct {
// Especifica o nome do campo
StudentId string `copier:"Id"`
StudentName string `copier:"Name"`
Address string
School string
Class string
}
func main() {
student := Student{
StudentId: "123",
StudentName: "jack",
Address: "usa",
School: "MIT",
Class: "AI",
}
src := make(map[string]Student)
src["a"] = student
src["b"] = student
dest := make(map[string]User)
if err := copier.CopyWithOption(&dest, &src, copier.Option{
IgnoreEmpty: false,
CaseSensitive: false,
DeepCopy: false,
Converters: []copier.TypeConverter{
{
SrcType: Student{},
DstType: User{},
Fn: func(src interface{}) (dst interface{}, err error) {
s, ok := src.(Student)
if !ok {
return User{}, errors.New("tipo errado")
}
return User{
Id: s.StudentId,
}, nil
},
},
},
FieldNameMapping: nil,
}); err != nil {
panic(err)
}
fmt.Printf("%+v\n", src)
fmt.Printf("%+v\n", dest)
}Saída:
map[a:{StudentId:123 StudentName:jack Address:usa School:MIT Class:AI} b:{StudentId:123 StudentName:jack Address:usa School:MIT Class:AI}]
map[a:{Id:123 Name: Address:} b:{Id:123 Name: Address:}]