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

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

青灯夜游
Release: 2023-01-11 09:23:06
Original
14565 people have browsed it

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")
      }
   */
}
Copy after login

Output:

equal
Copy after login

Remove the comment prompt:

invalid operation: a[:] == b[:] (slice can only be compared to nil)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template