Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the size of the array in go

Tags:

arrays

go

I have tried len() function but it gives the declared value. The size() function gives an error.

Code:

package main
var check [100]int
func main() {
    println(len(check))
}

The output is 100 here, I need the total items in array (i.e. 0).

like image 311
Revanth Penugonda Avatar asked Mar 11 '16 10:03

Revanth Penugonda


1 Answers

Arrays in Go are fixed sizes: once you create an array in Go, you can't change its size later on. This is so to an extent that the length of an array is part of the array type (this means the types [2]int and [3]int are 2 distinct types). That being said the length of a value of some array type is always the same, and it is determined by its type. For example the length of an array value of type [100]int is always 100, (which can be queried using the built-in function len()).

Spec: Array Types:

The length is part of the array's type; it must evaluate to a non-negative constant representable by a value of type int. The length of array a can be discovered using the built-in function len.

If you're looking for the answer to "How many elements have been set?", that is not tracked in Go. The "total items in array" you're looking for is also always the same as the array length: when you create an array in Go, all elements in the array are initialized to the zero-value of the element's type (unless otherwise specified e.g. by using a composite literal).

For example after this line:

var arr [100]int

The array arr already has 100 ints, all being 0 (because that is the zero-value of type int). After the following line:

var arr2 = [3]int{1, 2, 3}

The array arr2 has 3 int elements, being 1, 2 and 3. And after the following line

var arr3 = [...]bool{3: true}

The array arr3 has 4 bool elements, being false, false, false and true (false is the zero value of type bool and we only specified the 4th element to be true which is at index 3).

Your question might have more meaning if you would ask about slices:

A slice is a descriptor for a contiguous segment of an underlying array and provides access to a numbered sequence of elements from that array.

So basically a slice is a "view" of some (contiguous) part of an array. A slice header or descriptor contains a pointer to the first value of the part it describes in the array, it contains a length and the capacity (which is the max value to which the length can be extended).

I really recommend to read the following blog posts:

The Go Blog: Go Slices: usage and internals

The Go Blog: Arrays, slices (and strings): The mechanics of 'append'

like image 73
icza Avatar answered Oct 20 '22 09:10

icza