Declaration and Initialization
This lesson describes the important concepts of array, i.e., how to use, declare and initialize them.
We'll cover the following
Introduction
In this chapter, we start by examining data-structures that contain a number of items, called collections, such as arrays (slices) and maps. Here, the Python influence is obvious. The array-type indicated by the [] notation is well-known in almost every programming language as the basic workhorse in applications.
The Go array is very much the same but has a few peculiarities. It is not as dynamic as in C, but to compensate, Go has the slice type. This is an abstraction built on top of Go’s array type. So to understand slices, we must first understand arrays. Arrays have their place, but they are a bit inflexible. Therefore, you don’t see them too often in Go code. Slices, though, are everywhere, and they are built on arrays to provide greater power and convenience.
Concept
An array is a numbered and fixed-length sequence of data items (elements) of the same type (it is a homogeneous data structure). This type can be anything from primitive types like integers or strings to self-defined types. The length must be a constant expression, that must evaluate to a non-negative integer value. It is part of the
type of the array, so arrays declared as [5]int
and [10]int
differ in type. The items can be accessed and changed through their index (their position). The index starts from 0, so the 1st element has index 0, the 2nd index 1, and so on (arrays are zero-based as usual in the C-family of languages).
The number of items, also called the length (called len) or size of the array, is fixed and must be given when declaring the array (length has to be determined at compile time in order to allocate the memory).
Remark: The maximum array length is 2Gb.
The format of the declaration is:
var identifier [len]type
For example:
var arr1 [5]int
Let’s visualize arr1
in memory
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy