个性化阅读
专注于IT技术分析

如何在Golang中检查字节切片的相等性?

点击下载

在Go语言中,切片比数组更强大、更灵活、更方便,是一种轻量级的数据结构。切片是一个可变长度的序列,它存储类似类型的元素,不允许在同一个切片中存储不同类型的元素。

如何在Golang中检查字节切片的相等性?在Go的字节切片中,你可以在Equal()函数的帮助下检查切片是否相等。如果两个切片相等,则返回true;如果两个切片不相等,则返回false。它是在bytes包下定义的,因此,为了访问Equals函数,必须在程序中导入bytes包。

语法如下:

func Equal(slice_1, slice_1 []byte) bool

在这里, 我们检查slice_1和slice_2并且此函数的返回类型为bool。让我们借助示例来讨论这个概念:

范例1:

// Go program to illustrate how to
// check the equality of the slices
package main
  
import (
     "bytes"
     "fmt"
)
  
func main() {
  
     // Creating and initializing slices of bytes
     // Using shorthand declaration
  
     slice_1 := []byte{ 'A' , 'N' , 'M' , 'A' , 'P' , 'A' , 'A' , 'W' }
      
     slice_2 := []byte{ 'A' , 'N' , 'M' , 'A' , 'P' , 'A' , 'A' , 'W' }
  
     // Checking the equality of the slices
     // Using Equal function
     res := bytes.Equal(slice_1, slice_2)
      
     if res == true {
      
         fmt.Println( "Slice_1 is equal to Slice_2" )
     } else {
      
         fmt.Println( "Slice_1 is not equal to Slice_2" )
     }
  
}

输出如下:

Slice_1 is equal to Slice_2

范例2:

// Go program to illustrate how to
// check the equality of the slices
package main
  
import (
     "bytes"
     "fmt"
)
  
func main() {
  
     // Creating and initializing 
     // slices of bytes
     // Using shorthand declaration
     slice_1 := []byte{ 'A' , 'N' , 'M' , 'A' , 'P' , 'A' , 'A' , 'W' }
      
     slice_2 := []byte{ 'g' , 'e' , 'e' , 'k' , 's' }
      
     slice_3 := []byte{ 'A' , 'N' , 'M' , 'A' , 'P' , 'A' , 'A' , 'W' }
  
     // Checking the equality of the slices
     // Using Equal function
     res1 := bytes.Equal(slice_1, slice_2)
     res2 := bytes.Equal(slice_1, slice_3)
     res3 := bytes.Equal(slice_2, slice_3)
     res4 := bytes.Equal([]byte( "srcmini" ), []byte( "srcmini" ))
     res5 := bytes.Equal([]byte( "Geeks" ), []byte( "GFG" ))
     res6 := bytes.Equal(slice_1, []byte( "P" ))
  
     // Displaying results
     fmt.Println( "Result 1:" , res1)
     fmt.Println( "Result 2:" , res2)
     fmt.Println( "Result 3:" , res3)
     fmt.Println( "Result 4:" , res4)
     fmt.Println( "Result 5:" , res5)
     fmt.Println( "Result 6:" , res6)
  
}

输出如下:

Result 1: false
Result 2: true
Result 3: false
Result 4: true
Result 5: false
Result 6: false

以上就是在Golang中检查字节切片的相等性的方法,希望可以帮到你,如有错误,欢迎在下方评论指出


赞(0)
未经允许不得转载:srcmini » 如何在Golang中检查字节切片的相等性?

评论 抢沙发

评论前必须登录!