Skip to content

Instantly share code, notes, and snippets.

@gregworley
Created September 29, 2010 20:15
Show Gist options
  • Save gregworley/603449 to your computer and use it in GitHub Desktop.
Save gregworley/603449 to your computer and use it in GitHub Desktop.
package main
import "fmt"
func main() {
m := make(map[string]int) //initialize
//map[keyType]valueType
m["Alice"] = 21 //Store Values to initialized
//array.
// m["keyType"] = valueType
// "Alice" is the key
// 21 is the value
m["Bob"] = 17
a := m["Alice"]
b := m["Bob"]
for k, v := range m {
fmt.Println(k, v)
}
fmt.Println("the value mapped to key Alice:", a)
fmt.Println("the value mapped to key Bob:", b)
c := m["Charlie"] //retrieving a value from a key that's not in the map c == 0
fmt.Println("c", c)
// map returns two values - the key's value and bool testing key's presence.
d, okd := m["Alice"] // d == 21, okd == true
e, oke := m["Charlie"] // e == 0, oke == false
fmt.Println("d, okd:",d, okd)
fmt.Println("e, oke:",e, oke)
// To remove a key/value entry from a map, flip it around and assign false as the second value:
m["Bob"] = 0, false // the value 0 could have been any int, it's the false that's important
f, okf := m["Bob"] //check the 2nd return-is "Bob" a valid key?
// b==0, okb == false
fmt.Println("f, okf:", f, okf)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment