Go Collection Flashcards
What is an Array ?
A collection with fixed length and similar datatype.
What is the long syntax of declaring array in GO ?
var <arrayName> [<arrayLength>]<dataType>
e.g. var myArray [3]int</dataType></arrayLength></arrayName>
How to initialise a declared array ?
Using the index.
e.g. myArray[1] = 12
What is the short syntax of creating and initialisation of array in a single line ?
myArray := [4]int{1,2,3,4}
What’s a slice ?
Slice is a collection of similar datatypes, whose length is not fixed.
It gets expand as new elements gets added and shrink as older elements gets removed.
How to initialise an empty array ?
It can be initialised with empty Curly braces.
e.g. myArray := [3]int{}
Is it mandatory to initialise variable in shorthand operator ?>
Yes.
How to create an empty slice in Go ?
Same syntax of Array without the length.
e.g. mySlice := []int{}
How to append a new element in existing slice ?
Built-in “append” function:
e.g. mySlice = append(mySlice, 23, 445)
How to get a “slice” of an array ?
By providing the upper index and lower index:
e.g. mySlice := myArray[ 3:8]
How to create slice of an array for all elements ?
DO NOT provide the lower and upper index
e.g. mySlice := myArray[:]
How to create a Map in Go ?
Using “map” keyword and providing datatype of both “key” and “value”:
e.g. myMap := map[string]int{}
How to initialise a Map during declaration ?
By Passing JSON like structure in “key” value format:
e.g. myMap := map[string]{“key”:12}
How to get a value from Map, after providing the Key ?
myMap[“key”]
How to re-assign a new Value to existing key in a map ?
myMap[“key”] = value
How to delete any key-value from a Map ?
Using inbuilt “delete” function.
e.g. delete(myMap, “key”)
What do you mean by “Homogeneity” of “Arrays, Slices and Maps”
Arrays, Slices and Maps are homogeneous, which means they can only hold similar data types.
Which collection in Go is “heterogeneous” ?
Struct (just like classes, it can have any type of fields and functions)
What is Struct ?
A Struct is a heterogeneous collection, which can hold data of different types.
How to declare a “Struct” ?
By using “Type” and “Struct” keyword:
e.g.
type user struct {
id int,
firstName string,
lastName string
}