Home > Backend Development > Golang > How Do I Determine the Size of a Go Array?

How Do I Determine the Size of a Go Array?

Barbara Streisand
Release: 2024-11-27 12:54:16
Original
839 people have browsed it

How Do I Determine the Size of a Go Array?

Determining the Size of an Array in Go

Arrays in Go are fixed in size, unlike slices. The size of an array is determined by its type and is declared at creation. Once created, the size of an array cannot be changed.

In your example code:

package main

var check [100]int

func main() {
    println(len(check))
}
Copy after login

The len() function retrieves the declared size of the array, which in this case is 100. However, you are looking to retrieve the number of elements in the array that have been set or initialized.

Go arrays are initialized with zero values for all elements. Therefore, the number of initialized elements in the array is always equal to the declared size. In your case, there are 0 initialized elements, but the size of the array is 100.

If you were using a slice, you could use the len() function to retrieve the number of elements in the slice, as slices can have a size that is less than the capacity. However, this is not applicable to arrays.

Therefore, to obtain the desired information in your example, you would have to manually track the number of elements initialized in the array.

The above is the detailed content of How Do I Determine the Size of a Go Array?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template