Range
The range
form of the for
loop iterates over a slice or map.
When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.
1 | var pow = []int{1, 2, 4, 8, 16, 32, 64, 128} |
You can skip the index or value by assigning to _
.
1 | for i, _ := row |
If you only want the index, you can omit the second variable.
for i := range pow
1 | func main() { |
Maps
A map maps keys to values.
The zero value of a map is nil
. A nil
map has no keys, nor can keys be added.
The make
function returns a map of the given type, initialized and ready for use.
1 | type Vertex struct { |
Mutate Maps
Insert or update an element in map m
:
m[key] = elem
Retrieve an element:
elem = m[key]
Delete an element:
delete(m, key)
Test that a key is present with a two-value assignment:
elem, ok := m[key]
: ok == true
if key
is in m
.
If key
is not in the map, then elem
is the zero value of the map’s element type.
1 | func main() { |
Functions
Functions are values too. They can be passed around just like other values. Function values may be used as function arguments and return values.
1 | func compute(fn func(float64, float64) float64) float64 { |
Closures
Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is “bound” to the variables.
For example, the adder
function returns a closure. Each closure is bound to its own sum
variable.
1 | func adder() func(int) int { |