Jump to content

Associative array/Iteration: Difference between revisions

→‎{{header|Go}}: add template example
(→‎{{header|Go}}: add template example)
Line 1,113:
 
=={{header|Go}}==
'''Language:'''
<lang go>myMap := map[string]int {
"hello": 13,
Line 1,132 ⟶ 1,133:
fmt.Printf("value = %d\n", value)
}</lang>
'''Standard library templates:'''
 
In addition to the for/range features of the language, the text/template and html/template packages of the standard library have map iteration features. Some differences worth noting:
* A single assigned value in a template is the map value. With the language for/range it is the key.
* Templates have no equivalent of _; a dummy variable must be used.
* In a template, if map keys are a comparable basic type, then iteration proceeds in key order. With the language for/range, iteration is in non-deterministic order.
 
<lang go>package main
 
import (
"os"
"text/template"
)
 
func main() {
m := map[string]int{
"hello": 13,
"world": 31,
"!": 71,
}
 
// iterating over key-value pairs:
template.Must(template.New("").Parse(`
{{- range $k, $v := . -}}
key = {{$k}}, value = {{$v}}
{{end -}}
`)).Execute(os.Stdout, m)
 
// iterating over keys:
template.Must(template.New("").Parse(`
{{- range $k, $v := . -}}
key = {{$k}}
{{end -}}
`)).Execute(os.Stdout, m)
 
// iterating over values:
template.Must(template.New("").Parse(`
{{- range . -}}
value = {{.}}
{{end -}}
`)).Execute(os.Stdout, m)
}</lang>
{{out}}
Note order by key.
<pre>
key = !, value = 71
key = hello, value = 13
key = world, value = 31
key = !
key = hello
key = world
value = 71
value = 13
value = 31
</pre>
 
=={{header|Groovy}}==
1,707

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.