CopierGolang 复制版
Copier 是 Golang 的复制版,它从一个结构复制到了另一个结构。它具有以下特点:
-
如果名字匹配,就从一个场景复制到另一个场景
-
如果方法名和场景名匹配,就从方法复制到场景
-
如果场景名和方法名匹配,就从场景复制到方法
-
从片复制到片
-
从结构复制到片
示例代码:
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 EmployeId int64 SuperRule string}func (employee *Employee) Role(role string) { employee.SuperRule = "Super " + role } user := User{Name: "Jinzhu", Age: 18, Role: "Admin"} employee := Employee{}Copy(&employee, &user) // employee => Employee{ Name: "Jinzhu", // Copy from field // Age: 18, // Copy from field // DoubleAge: 36, // Copy from method // EmployeeId: 0, // Just ignored // SuperRule: "Super Admin", // Copy to method // } // Copy struct to slice user := User{Name: "hello", Age: 18, Role: "User"} employees := []Employee{}Copy(&employees, &user) // employees => [{hello 18 0 36 Super User}] // Copy slice to sliceusers := []User{{Name: "Jinzhu", Age: 18, Role: "Admin"}, {Name: "jinzhu 2", Age: 30, Role: "Dev"}} employees := []Employee{}Copy(&employees, &users) // employees => [{hello 18 0 36 Super User} {Jinzhu 18 0 36 Super Admin} {jinzhu 2 30 0 60 Super Dev}]
评论