Golang中好用的三方工具包lancet使用
项目地址
lancet源码项目地址
自己练习的项目:a_lancet_tests
slice 有结构体切片的转换
package a_lancet_tests import ( "fmt" "github.com/duke-git/lancet/v2/slice" "testing" ) // slice.Map: Notice 结构体切片之间的转换 type teacher struct { Name string Age int } type teacherRPC struct { Name string Age int } func TestSliceChange(t *testing.T) { tr1 := teacherRPC{Name: "whw", Age: 22} tr2 := teacherRPC{Name: "naruto", Age: 23} trSlice := []*teacherRPC{&tr1, &tr2} // Notice 转化成 *teacher 组成的切片! tSlice := slice.Map(trSlice, func(index int, item *teacherRPC) *teacher { return &teacher{ Name: item.Name, Age: item.Age, } }) fmt.Printf(">> %T, %v \n", tSlice, tSlice) // []*a_lancet_tests.teacher, [0x1400000c108 0x1400000c120] } // slice.Map: 返回结构体切片中某个属性组成的切片 func TestTT123(t *testing.T) { type student struct { sid int name string } lst := make([]*student, 0) for i := 0; i < 5; i++ { currStu := student{ sid: i, name: fmt.Sprintf("whw-%v", i), } lst = append(lst, &currStu) } ret := slice.Map(lst, func(index int, item *student) string { return item.name }) fmt.Println("ret: ", ret) // [whw-0 whw-1 whw-2 whw-3 whw-4] }
~~~
maputil
package a_lancet_tests import ( "fmt" "github.com/duke-git/lancet/v2/maputil" "testing" ) func TestS1(t *testing.T) { m1 := map[string]int{ "a1": 1, "a2": 22, "a3": 34, "a4": 66, } // ForEach maputil.ForEach(m1, func(key string, val int) { fmt.Println("key: ", key, "val: ", val) }) /* key: a1 val: 1 key: a2 val: 22 key: a3 val: 34 key: a4 val: 66 */ // Filter filterFunc := func(_ string, val int) bool { return val > 30 } ret := maputil.Filter(m1, filterFunc) fmt.Println("ret: ", ret) // ret: map[a3:34 a4:66] }
~~~