lean into examples
This commit is contained in:
43
examples/maps/maps.go
Normal file
43
examples/maps/maps.go
Normal file
@@ -0,0 +1,43 @@
|
||||
// Maps are Go's built-in associative data type (sometimes
|
||||
// called "hashes" or "dicts" in other languages).
|
||||
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
// To create an empty map, use the builtin `make`:
|
||||
// `make(map[key-type]val-type)`.
|
||||
m := make(map[string]int)
|
||||
|
||||
// Set key/value pairs using typical `name[key] = val`
|
||||
// syntax.
|
||||
m["k1"] = 7
|
||||
m["k2"] = 13
|
||||
|
||||
// Printing a map with e.g. `Println` will show all of
|
||||
// its key/value pairs, which can be useful for
|
||||
// debugging.
|
||||
fmt.Println("map:", m)
|
||||
|
||||
// Get a value for a key with `name[key]`.
|
||||
v1 := m["k1"]
|
||||
fmt.Println("v1: ", v1)
|
||||
|
||||
// The builtin `len` function returns the number of
|
||||
// key/value pairs when called on a map.
|
||||
fmt.Println("len:", len(m))
|
||||
|
||||
// The builtin `delete` removes key/value pairs from
|
||||
// a map
|
||||
delete(m, "k2")
|
||||
fmt.Println("map:", m)
|
||||
|
||||
// The optional second return value when getting a
|
||||
// value from a map indiciates if the key was present
|
||||
// in the map. This can be used to disambiguate
|
||||
// between missing keys and keys with zero values
|
||||
// like `0` or `""`.
|
||||
_, prs := m["k2"]
|
||||
fmt.Println("prs:", prs)
|
||||
}
|
||||
6
examples/maps/maps.sh
Normal file
6
examples/maps/maps.sh
Normal file
@@ -0,0 +1,6 @@
|
||||
$ go run maps.go
|
||||
map: map[k1:7 k2:13]
|
||||
v1: 7
|
||||
len: 2
|
||||
map: map[k1:7]
|
||||
prs: false
|
||||
Reference in New Issue
Block a user