You might want to read the previous post in the series.
Composite types created by combining the basic types like int, float etcetra.
Arrays
- An array is a fixed length sequence of zero or more elements of particular type
- Because of the fixed length constraints, Arrays are rarely used in Go
- if “…” appears in place of length, that means the length of array is determined by number of initialisers
- Size of array is part of it’s type, so [7] int is different from 9[int]
Output: Element at index is 2 Length of array is 3 Index is 0, and value is 1 Index is 1, and value is 2 Index is 2, and value is 3 Length of array is 3
Slices
Slices are variable length sequences of elements the same type. A slice type is []T where T is the type of element.
- A slice is a dynamically-sized flexible view into the elements of an array
- A slice has three components: A pointer, length and a capacity
- Unlike Arrays, slices are not comparable. We can not use “==” operator to test whether both slices have same elements or not
- The built-in append function append s items to slices
Output: [Sachin Ponting Waugh] [Zaheer Waqar Lee] [Zaheer Waqar Lee] [ Sachin Ponting Waugh Zaheer Waqar Lee McGrath]
Maps
- Map is an unordered collection of key and value pair
- Keys are distinct
- Update, insert, delete operations are in constant time
- Key must be comparable using “==”
- Maps can not be compared with each other
Output: map[0:Harsh 1:Yash] map[0:Harsh] Roll number of Harsh is 0 Roll number of Jain is 1
Struct
A struct is an aggregate data type that groups together zero or more named values of arbitrary types as a single entity. Like student data containing it’s id, name, class etc.
Output: ABC lives in XYZ and studies in X
- If all the fields of struct are comparable, struct is comparable
JSON
- JavaScript Object Notation (JSON) is a standard notation for sending and receiving structured information
- Converting from Go data structure to JSON is called marshaling
- Converting from JSON to Go data structure is called unmarhsaling
Output: map[key1:value1 key2:value2 key3:value3] {"key1":"value1","key2":"value2","key3":"value3"} { "key1":"value1", "key2":"value2", "key3":"value3" } map[key1:value1 key2:value2 key3:value3]
One thought on “GoLang Journey – Composite Types”