惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
News and Events Feed by Topic
GbyAI
GbyAI
博客园 - Franky
宝玉的分享
宝玉的分享
Blog — PlanetScale
Blog — PlanetScale
Google DeepMind News
Google DeepMind News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
人人都是产品经理
人人都是产品经理
Microsoft Azure Blog
Microsoft Azure Blog
The Register - Security
The Register - Security
腾讯CDC
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
I
InfoQ
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Engineering at Meta
Engineering at Meta
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
F
Full Disclosure
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Vercel News
Vercel News
博客园 - 【当耐特】
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Schneier on Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Project Zero
Project Zero
量子位
M
MIT News - Artificial intelligence
Stack Overflow Blog
Stack Overflow Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
美团技术团队
Attack and Defense Labs
Attack and Defense Labs
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Blog of Author Tim Ferriss
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
罗磊的独立博客
P
Proofpoint News Feed
Schneier on Security
Schneier on Security
Spread Privacy
Spread Privacy
S
SegmentFault 最新的问题
L
LINUX DO - 最新话题
Simon Willison's Weblog
Simon Willison's Weblog
爱范儿
爱范儿
博客园 - 聂微东
A
About on SuperTechFans
PCI Perspectives
PCI Perspectives
D
Docker

文章列表 on polarisxu

通过一个例子让你彻底掌握 Go 工作区模式 这道题正确率竟然只有 22% Go 开源项目推荐:一个简单的 Go 练手项目 go test 如何禁用缓存? Go1.18 快讯:constraints 包被移除标准库 跟着 Go 作者学泛型 「2022 版」轻松搞定 Go 开发环境 鹅厂小哥用行动反对加班:程序员加班能被终结吗? Go 为什么选择 Gopher 作为吉祥物? 本地如何配置多个 GitHub/Gitee 账号? 为 Java 开发者准备的 Go 教程 02:Java 有而 Go 无 GitHub 发现了 studygolang 项目依赖的漏洞 Typora 宣布收费后,这款开源 Markdown 编辑器火了 为 Java 开发者准备的 Go 教程 01:漫游了 我的 2021 年终总结 泛型版 singleflight:Go 中如何防止缓存击穿? 2021 年你写了多少代码?这个 Go 工具帮你统计 Go1.18 新特性:TryLock Go 泛型入门教程 程序员瑞士军刀:各种结构的转换工具 终于有 Go 版的 Elasticsearch 了 Go泛型系列:maps 包讲解 Go 1.18 中的 any 是什么? Go1.18 快讯:新的 IP 包 Go编程模式:详解函数式选项模式 Nginx 竟然也有 playground — Go 语言构建的 Go泛型系列:Go1.18 类型约束那些事 Go1.18 快讯:Module 工作区模式 Go1.18 快讯:新增的 Cut 函数太方便了 Go1.18 快讯:废弃了这个 API Go1.18 快讯:新增字符串 Clone API Go:如何获得项目根目录? Go 如何获取和设置环境变量 重磅变动:更快找到微信公众号里的Go文章 Go 这样设置版本号:我们的项目也可以 假期结束,推荐 2 本 manning 出的 Go 图书 Go Fiber 框架系列教程 04:测试应用 Go Fiber 框架系列教程 03:中间件 Go泛型系列:提前掌握Go泛型的基本使用 推荐一个 Go GUI 实战项目 Go Fiber 框架系列教程 02:详解相关 API 的使用 Go Fiber 框架系列教程 01: 和 Express 对比学习 Go Module:私有不合规库怎么解决引用问题 Go1.17 新特性:go get 变了 Go1.17 新特性:testing 包的相关变化 StackOverflow 上关于 Go select 死锁的问题 新书推荐:用 Gin 框架构建分布式应用 Go 官网要变天。。。 Gin 这是要成为 Go 官方框架? 扬眉吐气:刚刚,Go 已经默认支持泛型了 Go 1.17 新特性:Module 有哪些变化? Go 第三方库推荐:类型转换如此简单 担心密码提交到 GitHub?建议使用这个 Go 开源工具 Go 的时间格式化为什么是 2006-01-02 15:04:05? GitHub 为 Go 社区带来安全支持 Go开源项目推荐:500行代码确认请求时间花在哪 一道关于 len 函数的诡异 Go 面试题解析 厉害了我的 Go:推荐系统都有开源实现 Go1.17 新特性:新版构建约束 这个工具真好:看看你的Go项目依赖有无漏洞 网友很强大,发现了Go并发下载的Bug Rust 劝退系列 09:函数 Go项目实战:一步步构建一个并发文件下载器 这本 Go 新书挺期待的:100 个常见错误 Go 启用新的官方问答社区 这是要干嘛?!微软招 Go 编译器全职开发人员 Go1.17 快报之标准库越来越注重易用性 Go1.17 新特性之切片变数组 回顾 Go 官网的演变史 站长8年前的Go代码竟然进入大厂的项目里了 Go图书翻译:一个好消息,一个坏消息 不怕烂尾!决定组织翻译这本 Go 图书 Rust 劝退系列 08:模式匹配 一本花了2.5年写成的Go免费在线图书 被黑惨了:一句话,说明自己会 Go,咋整? Go1.16 中的新函数 signal.NotifyContext 怎么用? Go 1.17 新特性提前学之测试执行随机化 Rust 劝退系列 07:流程控制 官方的 Go 多版本管理:使用和原理 Rust新书:给你一个劝退的理由 周刊题解:常量表达式这个规则应该了解下 盘点那些使用 Go 语言的国外公司 编写了50万行Go代码是一种什么体验 Rust 劝退系列 06:常量 Uber 使用 Go 的规模这么大?!都自己定制的 Go 编译器了 Go Team Leader — rsc 大神新开源了一个库,增强模板功能 再一次看到了 Go 的节制:int128 类型要不要支持? Rust 劝退系列 05:复合数据类型 「卷」有理论依据:海勒姆定律—Go又是怎么卷的 Go 真的也可以进行 GUI 开发:还有这样的图书呢 Rust 劝退系列 04:基本数据类型 我的 Go 语言书单 Rust 劝退系列 03:变量 我又来推荐免费 Go 新书了:一本用 Go 讲架构的书 注释竟然还有特殊用途?一文解惑 //go:linkname 指令 这个功能,公众号、微信群会不会被玩坏? 一道 Go 闭包题,面试官说原来自己答错了:面别人也涨知识 Rust 劝退系列 02:第一个 Rust 程序 Rust 劝退系列 01:打造开发环境 答应我,这次一定彻底搞懂 Go 中的类型别名
Go泛型系列:slices 包讲解
2021-11-27 · via 文章列表 on polarisxu

大家好,我是 polarisxu。

前段时间,Russ Cox 明确了泛型相关的事情 ,原计划在标准库中加入泛型相关的包,改放到 golang.org/x/exp 下。

目前,Go 泛型的主要设计者 ianlancetaylor 完成了 slices 和 maps 包的开发,代码提交到了 golang.org/x/exp 中,如果经过使用、讨论等,社区认可后,预计在 1.19 中会合入标准库中。

今天,通过学习 slices 包,掌握 Go 泛型的使用方法。

标准库有 bytes 和 strings 包,分别用来处理 []byte 和 string 类型,提供了众多方便的函数,但对普通的 slice,却没有相关的包可以使用。

比如 bytes 和 strings 都有 Index 函数,用来在 []byte 或 string 查找某个 byte 或字符串的索引。对于普通的 slice,没法写一大堆包来处理,只能用户自己实现,这也是没有泛型的弊端。

提供 bytes 和 strings,主要是因为它们使用频率高

现在有了泛型,可以实现一些便利的 slice 操作方法,必须要针对某一个具体类型的 slice 都实现一遍相同的功能。

02 constraints 包

继续讲解 slices 包之前,先看看 contraints 包。

该包定义了一组用于类型参数(泛型)的有用约束,这个包已经确定在 Go 1.18 标准库中包含,截止目前(2021.11.27),该包定义了 6 个约束类型:

// Signed is a constraint that permits any signed integer type.
// If future releases of Go add new predeclared signed integer types,
// this constraint will be modified to include them.
type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

// Unsigned is a constraint that permits any unsigned integer type.
// If future releases of Go add new predeclared unsigned integer types,
// this constraint will be modified to include them.
type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

// Integer is a constraint that permits any integer type.
// If future releases of Go add new predeclared integer types,
// this constraint will be modified to include them.
type Integer interface {
	Signed | Unsigned
}

// Float is a constraint that permits any floating-point type.
// If future releases of Go add new predeclared floating-point types,
// this constraint will be modified to include them.
type Float interface {
	~float32 | ~float64
}

// Complex is a constraint that permits any complex numeric type.
// If future releases of Go add new predeclared complex numeric types,
// this constraint will be modified to include them.
type Complex interface {
	~complex64 | ~complex128
}

// Ordered is a constraint that permits any ordered type: any type
// that supports the operators < <= >= >.
// If future releases of Go add new ordered types,
// this constraint will be modified to include them.
type Ordered interface {
	Integer | Float | ~string
}

前面 3 个是整型相关类型约束,Float 是浮点型约束,Complex 是负数类型约束,而 Ordered 表示支持排序的类型约束,表示支持大小比较的类型。

之前文章:《Go泛型系列:Go1.18 类型约束那些事》 提到,约束语法变更了,一个是 | 符号,一个是 ~,上面定义中,很多地方都用到了 ~ 符号,它表示出了类型自身,底层类型是它的类型也适用该约束。

03 slices 包详解

目前,slices 包有 14 个函数,可以分成几组:

  • slice 比较
  • 元素查找
  • 修改 slice
  • 克隆 slice

其中,修改 slice 分为插入元素、删除元素、连续元素去重、slice 扩容和缩容。

slice 比较

比较两个 slice 中的元素,细分为是否相等和普通比较:

func Equal[E comparable](s1, s2 []E) bool
func EqualFunc[E1, E2 any](s1 []E1, s2 []E2, eq func(E1, E2) bool) bool
func Compare[E constraints.Ordered](s1, s2 []E) int
func CompareFunc[E1, E2 any](s1 []E1, s2 []E2, cmp func(E1, E2) int) int

其中 comparable 约束是语言实现的(因为很常用),表示可比较约束(相等与否的比较)。主要,其中的 E、E1、E2 等,只是泛型类型表示,你定义时,可以用你喜欢的,比如 T、T1、T2 等。

看一个具体的实现:

func Equal[E comparable](s1, s2 []E) bool {
	if len(s1) != len(s2) {
		return false
	}
	for i, v1 := range s1 {
		v2 := s2[i]
		if v1 != v2 {
			return false
		}
	}
	return true
}

没有什么特别的,只不过把 s1、s2 当成同类型的 slice 进行操作而已。

元素查找

在 slice 中查找某个元素,分为普通的所有查找和包含判断:

func Index[E comparable](s []E, v E) int
func IndexFunc[E any](s []E, f func(E) bool) int
func Contains[E comparable](s []E, v E) bool

其中,IndexFunc 的类型参数没有使用任何约束(即用的 any),说明查找是通过 f 参数进行的,它的实现如下:

func IndexFunc[E any](s []E, f func(E) bool) int {
	for i, v := range s {
		if f(v) {
			return i
		}
	}
	return -1
}

参数 f 是一个函数,它接收一个参数,类型是 E,是一个泛型,和 IndexFunc 的第一个参数类型 []E 的元素类型保持一致即可,因此可以直接将遍历 s 的元素传递给 f。

修改 slice

一般不建议做相关操作,因为性能较差。如果有较多这样的需求,可能需要考虑更换数据结构。

// 往 slice 的位置 i 处插入元素(可以多个)
func Insert[S ~[]E, E any](s S, i int, v ...E) S
// 删除 slice 中 i 到 j 的元素,即删除 s[i:j] 元素
func Delete[S ~[]E, E any](s S, i, j int) S
// 将连续相等的元素替换为一个,类似于 Unix 的 uniq 命令。Compact 修改切片的内容,它不会创建新切片
func Compact[S ~[]E, E comparable](s S) 
func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S
// 增加 slice 的容量,至少增加 n 个
func Grow[S ~[]E, E any](s S, n int) S
// 移除没有使用的容量,相当于缩容
func Clip[S ~[]E, E any](s S) S

以上类型约束都包含了两个:

  • S ~[]E:表明这是一个泛型版 slice,这是对 slice 的约束。注意 [] 前面的 ~,表明支持自定义 slice 类型,如 type myslice []int
  • E any 或 E comparable:对上面 slice 元素类型的约束。

克隆 slice

即获得 slice 的副本,会进行元素拷贝,注意,slice 中元素的拷贝是浅拷贝,非值类型不会深拷贝。

func Clone[S ~[]E, E any](s S) S {
	// Preserve nil in case it matters.
	if s == nil {
		return nil
	}
	return append(S([]E{}), s...)
}

04 总结

因为泛型的存在,同样的功能,对不同类型的 slice 再也不用写多份代码。因为一些功能很常见,因此 Go 官方将其封装,将来会在标准库中提供。

出于谨慎考虑,slices 包不会在 1.18 中包含,如果你需要用到 slices 中的功能,可以采用从 slices 代码中复制的方式,个人觉得依赖 golang.org/x/exp 还是不太好。

slices 源码地址:https://github.com/golang/exp/blob/master/slices/slices.go