Home>Article>Backend Development> What is the difference between arrays and slices in go language?

What is the difference between arrays and slices in go language?

青灯夜游
青灯夜游 Original
2020-12-08 17:12:37 14415browse

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.

What is the difference between arrays and slices in go language?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn