If you have some experience in other programming languages like C or Java, you would know about arrays. To get things started, just imagine slices to be like arrays, with an abstraction layer and plethora of extra features. They are one of the key data types in Golang, dynamically sized and more powerful than arrays. In this blog, we will take a detailed look at slices and by the end of it, you should have no issues working with slices.
Let’s begin with a program, shall we?
var GuitarBrands = [] string{}
When you insert {}, you are initializing it.
‘Type of GuitarBrands is [] string’
Now, we move on to a fun part. In this section, we will take a look at further application of append and set a range on the slice. In this case, first, you should have a look at the program, then we will get into the explanation.
Explanation:
Using make()
It is a different way of creating slices. Here, you first have to define the type of data you require, following which you have to state the size.Let us have a look at the program.
Explanations:
Here registrationnumbers is the slice. And we are using make (). The slice is of type int and it consists of 4 elements. So, we assign the different values as per the position. Now, if you plan to include further numbers, you can do so by using the append (). And when you execute the program, you get output
[111 213 139 413 499 387 87]. So the slice initially had a size for 4 elements. Upon requesting memory allocation, it was increased further. As you can see, it saves a lot of memory, time and performance optimization is great.
Yes, you can easily do that in slices with the help of sort package. If you wish to arrange the numbers in ascending order, all you have to do is use sort.Ints
Once you understand the working of slices, you will be able to understand the databases easily. So, it is imperative that you have a thorough working knowledge of slices. And the best way to enhance your understanding is to code and execute programs. So, get cracking!