Home >Backend Development >Golang >What is the method for array comparison in Go language?
In the Go language, you can use the comparison operator "==" or "!=" to perform array comparison to determine whether two arrays are equal; only when all elements of the two arrays are equal Arrays must be equal, and two arrays of different types cannot be compared, otherwise the program will not be able to complete compilation.
The operating environment of this tutorial: Windows 10 system, GO 1.11.2, Dell G3 computer.
Compare two arrays for equality
If the two array types are the same (including the length of the array and the type of elements in the array) Below, we can directly use comparison operators (== and !=) to determine whether two arrays are equal. The arrays are equal only when all elements of the two arrays are equal. Two arrays of different types cannot be compared. array, otherwise the program will not complete compilation.
package main import ( "fmt" ) func main() { //通过 == 来比较数组 arr1 := [3]string{"Hello", "php中文网", "PHP"} arr2 := [3]string{"Hello", "php中文网", "PHP"} fmt.Println("arr1 == arr2 ", arr1 == arr2) }
Output:
arr1 == arr2 true
defines two arrays that both contain three elements. The elements of the arrays are the same. Then, we use == to compare the two arrays, and the result returns true. That is, the two arrays are equal.
Comparison of arrays with different lengths
Arrays with different lengths cannot be compared through == and !=
package main import ( "fmt" ) func main() { //数组长度不同,不可以通过 == 来比较数组 arr1 := [3]string{"Hello", "php中文网", "hi"} arr2 := [2]string{"Hello", "php中文网"} fmt.Println("arr1 == arr2 ", arr1 == arr2) }
After the program is run, the console The output is as follows:
# command-line-arguments ./main.go:9:35: invalid operation: arr1 == arr2 (mismatched types [3]string and [2]string)
The array arr1 we defined has three elements, and the array arr2 has two elements. Then, we use == and != to compare the two arrays. The program directly panics, so the lengths are different. Arrays cannot be compared.
Recommended learning: Golang tutorial
The above is the detailed content of What is the method for array comparison in Go language?. For more information, please follow other related articles on the PHP Chinese website!