iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > GO >使用golang怎么判断slice是否相等
  • 329
分享到

使用golang怎么判断slice是否相等

2023-06-14 10:06:19 329人浏览 八月长安
摘要

这期内容当中小编将会给大家带来有关使用golang怎么判断slice是否相等,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。slice相等的定义我们选择最常见的需求,也就是当两个slice的类型和长度相同,

这期内容当中小编将会给大家带来有关使用golang怎么判断slice是否相等,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

slice相等的定义

我们选择最常见的需求,也就是当两个slice的类型和长度相同,且相等下标的值也是相等的,比如:

a := []int{1, 2, 3}b := []int{1, 2, 3}c := []int{1, 2}d := []int{1, 3, 2}

上述代码中ab是相等的,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是否相等了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注编程网GO频道。

您可能感兴趣的文档:

--结束END--

本文标题: 使用golang怎么判断slice是否相等

本文链接: https://www.lsjlt.com/news/269897.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作