Significance of Go — Part 4 (Arrays, Slices, Maps and Structs)

Arrays

In this section, I am going to show you the similarity/difference between the arrays and the slices in Go.

If you have not initialized an array the default values will be zeros.

Consider the below screenshot with its outputs.

Default values are initialized as zero values
Finding the length of an array

Use […] instead of length if the length of the array should be decided by the number of elements in the array automatically.

Please find the below screenshot and check the output you got.

Use […] when declaring the array

Can compare two arrays using == operator.

As shown in the below screenshot when you compare two arrays, if they are similar the output will be true, else false.

Comparing two arrays
Error when you try to compare different type of arrays

Slices

Since array has a fixed length, there is a need for another collection type which can be dynamic in size. This is the place where a slice comes into action.

A slice on top of an array

A slice can be defined on top of an array if you like. Consider the below code segment and its output.

A slice on top of an array
Relationship between the slice and the array
  • In line 13, we have changed the last element of slice to 200.

A slice without an explicit underline array

Refer to the below screenshot to learn how to define a slice without an explicitly defined underline array.

A slice without an explicit underline array
append function with slices

Maps

A map is a collection of key-value pairs. It will map each of the values with the corresponding key so that the user can access the values using the keys as shown in the below screenshot.

Define a map and access the values

Structs

Arrays, slices, and maps do not have the ability to associate discrete data types together. A struct is the only collection type that has this ability. A struct can be defined as follows.

type book struct {
Title string
Sold bool
Pages int
}
Three ways to initialize a struct

Conclusion

In this article, we discussed arrays, slices, maps and structs in Go. Further, we identified how a slice is different from the traditional data type array and the characteristics of those. Also, we learned the uniqueness of a struct that has the ability to associate different data types together. To learn more about arrays and slices please refer to the below link.

Previous Articles

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store