登录
首页 >  Golang >  Go教程

Go语言中的Slice链式操作方法是什么

来源:亿速云

时间:2023-05-02 17:31:56 118浏览 收藏

积累知识,胜过积蓄金银!毕竟在##column_title##开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《Go语言中的Slice链式操作方法是什么》,就带大家讲解一下Slice、go语言知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

今天小编给大家分享一下Go语言中的Slice链式操作方法是什么的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

示例

首先模拟一个业务场景,有订单、产品、自定义订单三个结构体,订单中包含多个产品:

1
2
3
4
5
6
7
8
9
10
11
12
13
type Order struct {
    Id       string
    Products []Product
}
 
type Product struct {
    Id    string
    Price int
}
 
type CustomOrder struct {
    Id string
}

初始化模拟数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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,
            },
        },
    },
}

接下来对订单列表做各种操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 过滤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}]
}
 
// 将每个订单里的产品展开,并映射为自定义订单
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}]
}
 
// 找到所有订单产品中价格最贵的那个产品
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}
}

原理

1
2
3
type List[T any] struct {
    list []any
}

将 go 中的原生切片包装成 List[T] 结构体,特别说明其中的泛型 T 是最终结果的元素类型,并不是原始传入切片的类型。

这样设计是因为 go 只能在构造结构体时指定泛型,因此将 List[T] 的泛型指定为最终结果的元素类型,就可以在操作完成后调用 Collect() 方法,得到最终的 T 类型切片,方便后面的业务逻辑使用。

因为 go 不支持在接受者函数中定义泛型,因此所有操作函数的参数和返回值类型只能定义为any,然后在函数体内转换为业务结构体使用,例如上面的 i.(Product).Price

此后将每一种操作,例如Filter、Map、Flat等,都返回List[T] 结构体,就可以实现链式操作。

实现

1
2
3
4
5
6
7
8
9
10
11
12
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 <p class="introduction">以上就是“Go语言中的Slice链式操作方法是什么”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注golang学习网行业资讯频道。</p><p>今天关于《Go语言中的Slice链式操作方法是什么》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!</p>
声明:本文转载于:亿速云 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>