詳解Go語言中的Slice鏈式操作
示例
首先模擬一個業(yè)務(wù)場景,有訂單、產(chǎn)品、自定義訂單三個結(jié)構(gòu)體,訂單中包含多個產(chǎn)品:
type Order struct {
Id string
Products []Product
}
type Product struct {
Id string
Price int
}
type CustomOrder struct {
Id string
}初始化模擬數(shù)據(jù):
var orders = []Order{
{
Id: "o1",
Products: []Product{
{
Id: "p1",
Price: 1,
},
{
Id: "p2",
Price: 2,
},
},
},
{
Id: "o2",
Products: []Product{
{
Id: "p3",
Price: 3,
},
{
Id: "p4",
Price: 4,
},
},
},
}接下來對訂單列表做各種操作:
// 過濾Id為o2的訂單
func TestFilter(t *testing.T) {
res := Lists[Order](orders).Filter(func(o any) bool {
return o.(Order).Id == "o2"
}).Collect()
t.Log(res) // [{o2 [{p3 3} {p4 4}]}]
}
// 將訂單列表映射為自定義訂單列表
func TestMap(t *testing.T) {
res := Lists[CustomOrder](orders).Map(func(o any) any {
return CustomOrder{
Id: "custom-" + o.(Order).Id,
}
}).Collect()
t.Log(res) // [{custom-o1} {custom-o2}]
}
// 將每個訂單里的產(chǎn)品展開,并映射為自定義訂單
func TestFlatAndMap(t *testing.T) {
res := Lists[CustomOrder](orders).
Flat(func(o any) []any {
return Lists[any](o.(Order).Products).ToList()
}).
Map(func(p any) any {
return CustomOrder{
Id: "ProductId-" + p.(Product).Id,
}
}).Collect()
t.Log(res) // [{ProductId-p1} {ProductId-p2} {ProductId-p3} {ProductId-p4}]
}
// 找到所有訂單產(chǎn)品中價格最貴的那個產(chǎn)品
func TestMax(t *testing.T) {
res, found := Lists[Product](orders).
Flat(func(o any) []any {
return Lists[any](o.(Order).Products).ToList()
}).
Max(func(i, j any) bool {
return i.(Product).Price > j.(Product).Price
})
t.Log(found, res) // true {p4 4}
}原理
type List[T any] struct {
list []any
}將 go 中的原生切片包裝成 List[T] 結(jié)構(gòu)體,特別說明其中的泛型 T 是最終結(jié)果的元素類型,并不是原始傳入切片的類型。
這樣設(shè)計是因為 go 只能在構(gòu)造結(jié)構(gòu)體時指定泛型,因此將 List[T] 的泛型指定為最終結(jié)果的元素類型,就可以在操作完成后調(diào)用 Collect() 方法,得到最終的 T 類型切片,方便后面的業(yè)務(wù)邏輯使用。
因為 go 不支持在接受者函數(shù)中定義泛型,因此所有操作函數(shù)的參數(shù)和返回值類型只能定義為any,然后在函數(shù)體內(nèi)轉(zhuǎn)換為業(yè)務(wù)結(jié)構(gòu)體使用,例如上面的 i.(Product).Price。
此后將每一種操作,例如Filter、Map、Flat等,都返回List[T] 結(jié)構(gòu)體,就可以實現(xiàn)鏈式操作。
實現(xiàn)
type List[T any] struct {
list []any
}
func Lists[T any](items any) *List[T] {
rv := reflect.ValueOf(items)
if rv.Kind() != reflect.Slice {
panic(fmt.Sprintf("not supported type: %v, please use slice instead", rv.Kind()))
}
l := rv.Len()
s := make([]any, 0, l)
for i := 0; i < l; i++ {
s = append(s, rv.Index(i).Interface())
}
return &List[T]{
list: s,
}
}
func (s *List[T]) Filter(fn func(any) bool) *List[T] {
l := make([]any, 0)
for _, e := range s.list {
if fn(e) {
l = append(l, e)
}
}
s.list = l
return s
}
func (s *List[T]) Map(fn func(any) any) *List[T] {
l := make([]any, 0)
for _, element := range s.list {
l = append(l, fn(element))
}
return &List[T]{
list: l,
}
}
func (s *List[T]) Flat(fn func(any) []any) *List[T] {
l := make([]any, 0)
for _, element := range s.list {
l = append(l, fn(element)...)
}
return &List[T]{
list: l,
}
}
func (s *List[T]) Sort(fn func(i, j any) bool) *List[T] {
if len(s.list) <= 0 {
return s
}
sort.SliceStable(s.list, func(i, j int) bool {
return fn(s.list[i], s.list[j])
})
return s
}
func (s *List[T]) Max(fn func(i, j any) bool) (T, bool) {
return s.Sort(fn).FindFirst()
}
func (s *List[T]) FindFirst() (T, bool) {
if len(s.list) <= 0 {
var nonsense T
return nonsense, false
}
return s.list[0].(T), true
}
func (s *List[T]) ToList() []any {
return s.list
}
func (s *List[T]) Collect() []T {
t := make([]T, 0)
for _, a := range s.list {
t = append(t, a.(T))
}
return t
}到此這篇關(guān)于詳解Go語言中的Slice鏈式操作的文章就介紹到這了,更多相關(guān)Go Slice鏈式操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
golang 數(shù)組去重,利用map的實現(xiàn)
這篇文章主要介紹了golang 數(shù)組去重,利用map的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
golang 微服務(wù)之gRPC與Protobuf的使用
這篇文章主要介紹了golang 微服務(wù)之gRPC與Protobuf的使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02
Go語言rune與字符串轉(zhuǎn)換的密切關(guān)系解析
這篇文章主要為大家介紹了Go語言rune與字符串轉(zhuǎn)換的密切關(guān)系示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12

