feat(Go-StudyExample):2020/12/29:新增【Go每日一库】copier复制不同结构体的同名属性

This commit is contained in:
Huangzj
2020-12-29 09:34:57 +08:00
parent 3d04c6dbad
commit ac81840d80
3 changed files with 64 additions and 0 deletions
+57
View File
@@ -0,0 +1,57 @@
/*
* @Author : huangzj
* @Time : 2020/12/29 9:16
* @Description
*/
package copier
import (
"fmt"
"github.com/jinzhu/copier"
"testing"
)
type User struct {
Name string
Age int
Role string
}
func (u *User) DoubleAge() int {
return u.Age * 2
}
type Employee struct {
Name string
Age int
SuperRole string
DoubleAge int
}
func (e *Employee) Role(role string) {
e.SuperRole = "通过role得到superRole" + role
}
func TestCopier(t *testing.T) {
user := User{Name: "dj", Age: 18}
users := []User{
{Name: "dj", Age: 18, Role: "Admin"},
{Name: "dj2", Age: 18, Role: "Dev"},
}
employee := Employee{}
var employees []Employee
//通过 【Role】 方法转换 User的Role属性到 Employee 的SuperRole -- 这个方法名好像要和被转换的一致才行
//通过 User 的 【DoubleAge】 方法转换到 Employee 的同名属性
_ = copier.Copy(&employee, &user)
fmt.Println(fmt.Sprintf("%#v\n", employee))
//结构体转换到数组,相当于append操作,不过是类型不同,复制具体属性
_ = copier.Copy(&employees, &user)
fmt.Println(fmt.Sprintf("%#v\n", employees))
//不同的结构体数组的转换
_ = copier.Copy(&employees, &users)
fmt.Println(fmt.Sprintf("%#v\n", employee))
}
+5
View File
@@ -0,0 +1,5 @@
获取包命令: go get github.com/jinzhu/copier
参考地址:https://segmentfault.com/a/1190000022008881
参考地址:https://github.com/darjun/go-daily-lib
+2
View File
@@ -39,6 +39,8 @@ json与struct之间转换处理工具使用示例
2020/12/28:新增【Go每日一库】sJson快速设置json串内容
2020/12/29:新增【Go每日一库】copier复制不同结构体的同名属性
# mod vendor模式加载包
通过go mod的方式加载的github上面的包会有报红的问题,但是包本身是可以运行的,这样就是会有一个问题,如果你想要点击去看方法的内容,没办法做到