本文摘自php中文网,作者藏色散人,侵删。
下面由golang教程栏目给大家介绍golang中判断两个slice是否相等与判断值下的 数组是否相等,希望对需要的朋友有所帮助!
在golang中我们可以轻松地通过==
来判断两个数组(array)是否相等,但遗憾的是slice并没有相关的运算符,当需要判断两个slice是否相等时我们只能另寻捷径了。
slice相等的定义
我们选择最常见的需求,也就是当两个slice的类型和长度相同,且相等下标的值也是相等的,比如:
1 |
|
上述代码中a
和b
是相等的,c
因为长度和a
不同所以不相等,d
因为元素的排列顺序和a
不同所以也不相等。
判断两个[]byte是否相等
为什么要单独将[]byte列举出来呢?
因为标准库提供了优化的比较方案,不再需要我们造轮子了:
1 2 3 4 5 6 7 8 9 |
|
使用reflect判断slice(数组)是否相等
在判断类型不是[]byte的slice时,我们还可以借助reflect.DeepEqual
,它用于深度比较两个对象包括它们内部包含的元素是否都相等:
1 |
|
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相等的原则是一样的,只不过它借助了一点运行时的“黑魔法”。
看例子:
1 2 3 4 5 6 7 8 |
|
手写判断
在golang中使用reflect通常需要付出性能代价,如果我们确定了slice的类型,那么自己实现slice的相等判断相对来说也不是那么麻烦:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
测试代码:
1 |
|
以上就是golang中判断两个slice是否相等的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
更多相关阅读请进入《Go》频道 >>
Go语言101
一个与时俱进的Go编程知识库。