Array, Slice, and Map: When can I use these on the Golang ?
Just like any other programming language, in the Go programming language, there are several types of data that can be used. One of the data types commonly used is the array data type.
Besides the array data type, there are several data types that are almost similar to or related to arrays, namely slices and maps.
In this article, we will discuss the use of arrays, slices and maps in golang
The array data type is a structured data type that can store a lot of data. usually the data stored has the same type.
In golang, the number of array elements will be set before the array elements are defined. and each element of the array has an index which will refer to the position of the element in the array.
The index on the array element will start from the number 0. As in the table above, the first array for the list of Southeast Asian countries is Indonesia.
The code above is an example of using an array showing 5 countries in Southeast Asia and the index for each element.
We are also allowed not to pre-set the number of elements by replacing the number of elements with three dots before defining the element.
Based on the above examples, an array can be used if we need to define the number of elements before the value of that element is displayed
Basically the function and concept of slices are almost the same as arrays. the difference is that in the slice type, we do not need to define the number of arrays either with numbers or with colons before defining elements. Therefore, slices are also often referred to as dynamic arrays
The code above is the result of using a slice, where there are only square brackets followed by the data type.
By using slices, we can also retrieve several existing array elements based on index.
The code above displays 2 data starting from the first index to before the third index.
As opposed to arrays, slices can be used when we don’t need to define the number of elements
The map data type is an associative data type and is also an unordered collection. the concept of using maps in golang is key-value based.
If the array or slice uses an index in the form of a number, the data type map index is a key. and the key for each element must be unique
The code above is an example of applying the map to Golang. The use of the map data type begins with writing the map, then continues the data type for keys and data types for values.
In the above example the key for the map uses the string data type while the value uses an integer. Indonesia, Malaysia, and Singapore are the map keys while 267000000, 31500000, and 5639000 are map values.
The map data type can be used when we already know the key and value to use. One example is when we are going to send an API request parameter.
At this point we already know the usage for arrays, slices and maps in golang. We can use these three data types as needed.