How can you understand the difference between array and slice two data types in Golang
Codes
package main
import (
"fmt"
)
func loopSlice(list []int) {
for _, v := range list {
fmt.Print(v, " ")
}
fmt.Print("\n")
}
func loopArray(list [4]int) {
for _, v := range list {
fmt.Print(v, " ")
}
fmt.Print("\n")
}
a := []int{2, 3, 4}
b := [4]int{1, 2, 3, 4}
loopSlice(a)
loopArray(b)
2 3 4
1 2 3 4
loopArray(a)
repl.go:1:11: cannot use <[]int> as <[4]int> in argument to loopArray
loopSlice(b)
repl.go:1:11: cannot use <[4]int> as <[]int> in argument to loopSlice
Conclusion
So the array
in golang is length fixed. If you want to use it. You have to clearly specify the length of that array.
Meanwhile, the slice
is different, you don’t have to specify the length of it.
Again:
- array:
var a [5]int
- slice:
var b []int