Explain length in array type
Explain length in array type
Array length is part of the type. [2]int and [3]int are different types and cannot be assigned directly to each other. Length must be a nonnegative integer-valued constant representable by int. Zero-length arrays are valid.
package main
import "fmt"
func main() { const size = 3 var a [size]int b := [...]int{1, 2, 3} a = b fmt.Printf("%T %v\n", a, a) fmt.Printf("%T\n", [2]int{})}Both a and b have type [3]int, even though their lengths are written differently. %T displays the type. A variable initialized with 3 cannot replace the constant size in an array type.
Expected output:
[3]int [1 2 3][2]intObserve length and capacity
package main
import "fmt"
func main() { var empty [0]int var fixed [4]int fmt.Println(len(empty), cap(empty)) fmt.Println(len(fixed), cap(fixed)) for range empty { fmt.Println("unreachable") }}For an array, len and cap both equal the declared length. Empty arrays are not nil. If length is chosen at run time, use a slice instead of [n]int with a variable n.
Expected output:
0 04 4Try it locally
Declare const width=2 and [width]string with A and B. Print its type, length, capacity and then the length of [0]string{}.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Arrays 06: Explain length in array type
Check the lesson objective before moving on.
Can [2]int be assigned directly to [3]int?
What may specify an array length?