Golang 如何检查字节的片断是否相等
在Go语言中slice比数组更强大、灵活、方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它存储了相似类型的元素,你不允许在同一个slice中存储不同类型的元素。
在Go的byes slice中,你可以在 Equal() 函数的帮助下检查slice的相等。如果两个片断都相等,这个函数返回true,如果两个片断都不相等,则返回false。它被定义在字节包下,因此,你必须在你的程序中导入字节包以访问Equals函数。
语法
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("GeeksforGeeks"),
[]byte("GeeksforGeeks"))
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
极客教程