卷!一个字形容了当今码农行业的现状。一层一层的代码结构,一个一个dto,entity,vo,req,resp。这些对象越来越多,让码农们非常劳于奔命,加一个字段,改一个字段,影响面有多少。代码量也越来越大。有可能一个代码,要建10多个数据对象。这虽然有点夸张,但体现了行业的乱象。
我是曾经写php代码的研发,由于php的并发能力的不足,和编译检错能力不足,导致行业用php越来越少了。但是不得不说,在php的时代,跟本不需要这么多对象,因为有一个强大的array,包罗万象。难度我们go、java都不能也通过这种方式实现吗?
Allright, 由此,MagicArray就诞生了,不用关心类型,不用关心空指针,不用创建哪么多数据对象,轻松数据转换。废话不多说,上代码:
DTO替代方式:
package main import ( "encoding/json" "fmt" arr "github.com/lingdor/magicarray" "time" ) type UserDTO struct { Id int `json:"userid"` Name string } type ScoreDTO struct { Score int ScoreTime time.Time } type AreaDto struct { CityId int City string } func dtosCommand() { user := UserDTO{ Id: 1, Name: "bobby", } score := ScoreDTO{ Score: 66, ScoreTime: time.Now(), } area := AreaDto{ CityId: 10000, City: "newyork", } mix, _ := arr.Merge(arr.ValueofStruct(user), score, area) mix = arr.Gets(mix, "Id", "City", "Score") if bs, err := json.Marshal(mix); err == nil { fmt.Println(string(bs)) } else { panic(err) } }
输出
{"userid":1,"City":"newyork","Score":66}
数据变换
package main import ( "encoding/json" "fmt" arr "github.com/lingdor/magicarray" ) type ColumnUserEntity struct { Id int `json:"uid"` UserName string IsMale bool } func columnCommand() { users := []ColumnUserEntity{ { Id: 1, UserName: "Bobby", IsMale: true, }, { Id: 2, UserName: "Lily", IsMale: false, }, } usersArr := arr.ValueOfSlice(users) usersArr = arr.WashColumnTag(usersArr, arr.WashTagJsonInitalLowerOpt()) if bs, err := json.Marshal(usersArr); err == nil { fmt.Println(string(bs)) } else { panic(err) } usersArr = arr.Column(usersArr, "UserName") if bs, err := json.Marshal(usersArr); err == nil { fmt.Println(string(bs)) } else { panic(err) } }
输出
["Bobby","Lily"]
tag操作
package main import ( "encoding/json" "fmt" arr "github.com/lingdor/magicarray" ) type UserEntity struct { Id int `json:"uid"` UserName string IsMale bool } func tagCommand() { users := []UserEntity{ { Id: 1, UserName: "Bobby", IsMale: true, }, { Id: 2, UserName: "Lily", IsMale: false, }, } usersArr := arr.ValueOfSlice(users) usersArr = arr.WashColumnTag(usersArr, arr.WashTagJsonInitalLowerOpt()) if bs, err := json.Marshal(usersArr); err == nil { fmt.Println(string(bs)) } else { panic(err) } }
输出
[ {"uid":1,"userName":"Bobby","isMale":true}, {"uid":2,"userName":"Lily","isMale":false} ]
参考:https://lingdor.medium.com/magicarray-use-to-data-translate-easily-8831b937bfc1
标签:arr,string,err,usersArr,json,MagicArray,Go,php,Id From: https://www.cnblogs.com/a-xu/p/17929336.html