copier 库

今天,推荐一个go开源库copier,这个库主要作用是把一个结构体变量的字段快速拷贝到另外一个结构体去。不用自己再一个字段一个字段的拷贝修改,非常方便。

引入这个库

go get -u github.com/jinzhu/copier

示例代码

package main

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

type User struct {
    Name         string
    Role         string
    Age          int32
    EmployeeCode int64 `copier:"EmployeeNum"` // specify field name
    // Explicitly ignored in the destination struct.
    Salary int
}

// 结构体方法
func (user *User) DoubleAge() int32 {
    return 2 * user.Age
}

type Employee struct {
    // Tell copier.Copy to panic if this field is not copied.
    Name string `copier:"must"`

    // Tell copier.Copy to return an error if this field is not copied.
    Age int32 `copier:"must,nopanic"`

    // Tell copier.Copy to explicitly ignore copying this field.  不拷贝。
    Salary int `copier:"-"`

    DoubleAge  int32
    EmployeeId int64 `copier:"EmployeeNum"` // specify field name 自定义tag,如果tag一致,那就拷贝。
    SuperRole  string
}

func main() {
    var (
        user      = User{Name: "Jinzhu", Age: 18, Role: "Admin", Salary: 200000}
        users     = []User{{Name: "Jinzhu", Age: 18, Role: "Admin", Salary: 100000}, {Name: "jinzhu 2", Age: 30, Role: "Dev", Salary: 60000}}
        employee  = Employee{Salary: 150000}
        employees = []Employee{}
    )

    copier.Copy(&employee, &user)  // copy user -> employee
    fmt.Printf("%#v \n", employee) //

    // Copy struct to slice
    copier.Copy(&employees, &user)

    fmt.Printf("[struct to slice] %#v \n", employees)

    // Copy slice to slice // slice 之间的拷贝
    employees = []Employee{}
    copier.Copy(&employees, &users)

    fmt.Printf("[Copy slice to slice] %#v \n", employees)

    // Copy map to map
    map1 := map[int]int{3: 6, 4: 8}
    map2 := map[int32]int8{}
    copier.Copy(&map2, map1)

    fmt.Printf("[Copy map to map] %#v \n", map2)
}

原理嘛,暂时没空看,大概率就是用反射解析出字段。和结构体tag。然后赋值了,2个入参都是指针变量,因此会修改变量。

Leave a Comment

Your email address will not be published. Required fields are marked *

PHP 8.1.1 - 16.257 ms, 0 Q