Home >Backend Development >Golang >What is the difference between arrays and slices in go language?
Difference: 1. Slices are pointer types, arrays are value types; 2. The length of arrays is fixed, but slices are not (slices can be regarded as dynamic arrays); 3. Slices have one more capacity than arrays (cap) attribute; 4. The bottom layer of the slice is an array.
The operating environment of this article: windows10 system, Go 1.11.2, thinkpad t480 computer.
Related recommendations: "go tutorial"
What does the following code output? What will be output if the comments are removed?
package main import ( "fmt" ) func main() { a := [2]int{5, 6} b := [2]int{5, 6} if a == b { fmt.Println("equal") } else { fmt.Println("not equal") } /* if a[:] == b[:] { fmt.Println("equal") } else { fmt.Println("not equal") } */ }
Output:
equal
Remove the comment prompt:
invalid operation: a[:] == b[:] (slice can only be compared to nil)
Explanation:
The difference between arrays and slices in the go language
● Slices are pointer types, arrays are value types
● The length of arrays is fixed, but slices are not (slices are dynamic arrays)
● There are more slices than arrays An attribute: capacity (cap)
● The bottom layer of the slice is an array
So, a and b define array types, and the array comparison is the same
However, a [:], b[:] are slices, and the equivalence judgment cannot be made between slices, and can only be judged with nil
For more programming-related knowledge, please visit:Programming Teaching! !
The above is the detailed content of What is the difference between arrays and slices in go language?. For more information, please follow other related articles on the PHP Chinese website!