golang中判断两个slice是否相等
时间:2021-04-19
来源:互联网
标签:
今天PHP爱好者给大家带来golang中判断两个slice是否相等与判断值下的 数组是否相等,希望对需要的朋友有所帮助!

在golang中我们可以轻松地通过==来判断两个数组(array)是否相等,但遗憾的是slice并没有相关的运算符,当需要判断两个slice是否相等时我们只能另寻捷径了。
slice相等的定义
我们选择最常见的需求,也就是当两个slice的类型和长度相同,且相等下标的值也是相等的,比如:
a := []int{1, 2, 3}b := []int{1, 2, 3}c := []int{1, 2}d := []int{1, 3, 2}
上述代码中a和b是相等的,c因为长度和a不同所以不相等,d因为元素的排列顺序和a不同所以也不相等。
判断两个[]byte是否相等
为什么要单独将[]byte列举出来呢?
因为标准库提供了优化的比较方案,不再需要我们造轮子了:
package mainimport (
"bytes"
"fmt")func main() {
a := []byte{0, 1, 3, 2}
b := []byte{0, 1, 3, 2}
c := []byte{1, 1, 3, 2}
fmt.Println(bytes.Equal(a, b))
fmt.Println(bytes.Equal(a, c))}
使用reflect判断slice(数组)是否相等
在判断类型不是[]byte的slice时,我们还可以借助reflect.DeepEqual,它用于深度比较两个对象包括它们内部包含的元素是否都相等:
func DeepEqual(x, y interface{}) bool
DeepEqual reports whether x and y are “deeply equal,” defined as follows. Two values of identical type are deeply equal if one of the following cases applies. Values of distinct types are never deeply equal.
…
Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal. Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil)) are not deeply equal.
这段话的意思不难理解,和我们在本文最开始时讨论的如何确定slice相等的原则是一样的,只不过它借助了一点运行时的“黑魔法”。
看例子:
package mainimport (
"fmt"
"reflect")func main() {
a := []int{1, 2, 3, 4}
b := []int{1, 3, 2, 4}
c := []int{1, 2, 3, 4}
fmt.Println(reflect.DeepEqual(a, b))
fmt.Println(reflect.DeepEqual(a, c))}
手写判断
在golang中使用reflect通常需要付出性能代价,如果我们确定了slice的类型,那么自己实现slice的相等判断相对来说也不是那么麻烦:
func testEq(a, b []int) bool {
// If one is nil, the other must also be nil.
if (a == nil) != (b == nil) {
return false;
}
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true}
测试代码:
package main import "fmt" func main() { a := []int{1, 2, 3, 4} b := []int{1, 3, 2, 4} c := []int{1, 2, 3, 4} fmt.Println(testEq(a, b)) fmt.Println(testEq(a, c))}
以上就是golang中判断两个slice是否相等的详细内容,更多请关注php爱好者其它相关文章!
-
什么是无理数 常见的无理数有哪些 无理数和有理数的区别 时间:2025-11-19 -
Linux中软连接和硬链接的区别、优缺点和应用场景等 时间:2025-11-19 -
什么是Hypervisor Hypervisor虚拟机监控程序详解 时间:2025-11-19 -
numeric是什么数据类型 decimal和numeric的区别 时间:2025-11-19 -
Java中public class和class的区别 时间:2025-11-19 -
Android中Activity跳转的两种实现方法 时间:2025-11-19
今日更新
-
上单行为是什么梗梗姐姐 揭秘游戏圈爆笑名场面真相
阅读:18
-
yy歪歪漫画官方主入口-yy漫画最新首页地址
阅读:18
-
币安风控Meme币交易原因解析及应对策略
阅读:18
-
yy漫画首页入口-热门章节一键畅读
阅读:18
-
超星网络学生登录入口 超星学生通官网网页版快速登录
阅读:18
-
币安风控申诉被拒的5大关键原因及解决方案
阅读:18
-
揭秘上等马梗出处:职场人秒懂的暗号文化,3秒get社畜生存法则
阅读:18
-
《龙骑士学园》官方入口地址
阅读:18
-
126邮箱登录入口-126邮箱网页版快速登录
阅读:18
-
币安风控机制是否受交易量阈值影响解析
阅读:18










