On Mon, Apr 8, 2019 at 2:41 PM Ian Lance Taylor <i...@golang.org> wrote:

> On Sun, Apr 7, 2019 at 6:19 PM Amit Saha <amitsaha...@gmail.com> wrote:
> >
> > I am seeing (what I think) a somewhat confusing behavior which I am not
> sure I understand. The working code example is at
> https://play.golang.org/p/GEqT4MiZQnq
> >
> >
> > Basically, I have a map which I am iterating over in a template:
> >
> >
> > m := map[int]string{
> > 1: "\"Hello\"\n",
> > 2: "\"World\"\n",
> > }
> >
> >
> > funcMap := template.FuncMap{
> > "testFunc": testFunc,
> > }
> >
> >
> > tmpl := template.New("test").Funcs(funcMap)
> > tmpl, err := tmpl.Parse(`
> >
> >
> > {{ range . }}{{. | testFunc}}{{end}}
> > `)
> > if err != nil {
> > log.Fatal("Error parsing template: ", err)
> >
> >
> > }
> >
> >
> > As you can see, I am not using the range $k, $v .. pattern to iterate
> over the map. But just using the generic "." pattern. My expectation here
> was that it would be iterating over the map's
> >
> > keys. However, it seems to be correctly doing what I wanted to do here,
> which is iterate over the values. How does that work?
>
> That's how the text/template package works.  Quoting
> https://golang.org/pkg/text/template:
>
>     If a "range" action initializes a variable, the variable is set to
> the successive elements of the iteration. Also, a "range" may declare
> two variables, separated by a comma:
>
>     range $index, $element := pipeline
>
>     in which case $index and $element are set to the successive values
> of the array/slice index or map key and element, respectively. Note
> that if there is only one variable, it is assigned the element; this
> is opposite to the convention in Go range clauses.
>

Thanks Ian.


-- 
http://echorand.me

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to