Go 语言的 Copier,将值从一个结构体复制到另一个结构体,以及更多功能
我是一个复制器,我将所有内容从一个复制到另一个
copier:"must" 强制复制字段IgnoreEmpty 也使用 copier:"override" 覆盖字段copier:"-" 排除字段,不进行复制要开始使用 Copier,请安装 Go 并运行 go get:
go get -u github.com/jinzhu/copier在你的应用程序中导入 Copier 以使用其复制功能
import "github.com/jinzhu/copier"type User struct {
Name string
Role string
Age int32
}
func (user *User) DoubleAge() int32 {
return 2 * user.Age
}
type Employee struct {
Name string
Age int32
DoubleAge int32
SuperRole string
}
func (employee *Employee) Role(role string) {
employee.SuperRole = "Super " + role
}
func main() {
user := User{Name: "Jinzhu", Age: 18, Role: "Admin"}
employee := Employee{}
copier.Copy(&employee, &user)
fmt.Printf("%#v\n", employee)
// Output: Employee{Name:"Jinzhu", Age:18, DoubleAge:36, SuperRole:"Super Admin"}
}copier:"-" - 忽略字段带有 copier:"-" 标签的字段在复制过程中会被 Copier 明确忽略。
type Source struct {
Name string
Secret string // We do not want this to be copied.
}
type Target struct {
Name string
Secret string `copier:"-"`
}
func main() {
source := Source{Name: "John", Secret: "so_secret"}
target := Target{}
copier.Copy(&target, &source)
fmt.Printf("Name: %s, Secret: '%s'\n", target.Name, target.Secret)
// Output: Name: John, Secret: ''
}copier:"must" - 强制字段复制copier:"must" 标签强制复制某个字段,如果该字段无法复制,则会导致 panic 或返回错误。
type MandatorySource struct {
Identification int
}
type MandatoryTarget struct {
ID int `copier:"must"` // 此字段必须被复制,否则会 panic 或报错。暂无开放 Issues,或尚未同步最近议题。