Go
Examples of how to create maps.
package main
import "fmt"
func main() {
// A map is an unordered collection of key-value pairs.
initials := make(map[string]string)
initials["JD"] = "Jack Doleman"
initials["PL"] = "Patrick Lock"
initials["HS"] = "Harry Saker"
fmt.Println(initials["HS"])
// You can return two values when accessing an element.
// The first value below returns zero value (empty string).
// The second (bool) value is for whether the lookup was successful.
name, ok := initials["BP"]
fmt.Println(name, ok)
// Here the lookup is successful
name, ok = initials["PL"]
fmt.Println(name, ok)
// Print if it's successful.
// N.B. A statement can procede conditionals.
if name, ok = initials["JD"]; ok {
fmt.Println(name, ok)
}
// You can also declare and initialise a new map a shorter way.
numbers := map[int]string{
1: "One",
2: "Two",
3: "Three",
4: "Four",
5: "Five",
}
fmt.Println(numbers)
// You can also store further values with an inner map.
people := map[int]map[string]string{
1: map[string]string{
"firstname": "Jack",
"middle initial": "A.",
"surname": "Doleman",
},
2: map[string]string{
"firstname": "Patrick",
"middle initial": "C.",
"surname": "Lock",
},
3: map[string]string{
"firstname": "Harry",
"middle initial": "V.",
"surname": "Saker",
},
}
if person, ok := people[3]; ok {
fmt.Println(person["firstname"], person["middle initial"], person["surname"])
}
}