Going from Swift to Go: Dictionaries/Maps

Going from Swift to Go: Dictionaries/Maps

Part 4 of the From Swift to Go series. In Swift, Dictionaries let you assign a variable to a key value; in Go, maps are used in the same manner. While the names are different, functionally the two are the same. Here we will discuss the syntax differences between the two.

Create Empty Dictionary/Map

In Swift, a dictionary is created similar to an array, such as var myArray : [Int] = [], except we declare two types (separated by a semicolon) instead of one. The first type is the key type, and the second type is the variable type. For example: var myDiction: [String : Int] = [:]. Note that we also add a semicolon to the empty brackets on the right side.

In Go, we can use the function make() to create empty arrays and dictionaries. The function requires an argument of the array or map you want to make; the syntax for a map is map[keyType]variableType . Put all this together, and we get something such as: myDiction := make(map[string]int) .

Create Dictionary/Map with Values

In Swift, instead of setting a dictionary equal to an empty list, we set it equal to an array of key/value pairs. For example: var myDiction: [String : Int] = ["alpha":1, "beta":2, "gamma":3]. Keep in mind that “alpha”, “beta”, and “gamma” are the keys here.

In Go, we no longer need to use the ‘make’ function, since the function is only for creating an empty array. Instead, we use the map function and add an array of values at the end. For example: myDiction := map[string]int{"alpha": 1, "beta": 2, "gamma": 3}. Here, “alpha”, “beta”, and “gamma” are still the keys.

Add a Value/Change a Value

The syntax for adding or changing a value in Swift and Go is… exactly the same. The dictionary/map name, followed by the key in “[]”, equals the desired value. Example: myDiction["delta"] = 4 . This is valid if delta has been used as a key, in which case the value is changed, or if delta has not been used as a key, in which case the key/value pair is added to the dictionary.