exp/template test for map's key exists

1,779 views
Skip to first unread message

Andrew Scott

unread,
Aug 1, 2011, 6:12:36 AM8/1/11
to golan...@googlegroups.com
Using the template package with a map[string]someType how do I create a pipeline that works with the "if" to test if a key exists in the map, without ranging the whole map?

Currently I'm using this to extract the element from the map for the key, but if the key is missing it errors :

type foo struct {
   ...
   MyMap map[string[interface{}
}

f := &foo{
   ...
   MyMap:map[string]interface{}{
      "one":&myType1,
      "two":&myType2,
      "three":&myType3,
   }

{{define "tmpl1"}}
   {{$myType1 := index .MyMap `one`}}
   {{/* do something with myType1 */}}
{{end}}

If the key "one" is missing from the map I receive the following error : 

"error calling index: index one not present in map"



roger peppe

unread,
Aug 1, 2011, 6:39:43 AM8/1/11
to golan...@googlegroups.com

i think this could be construed as a bug.

i'd expect the index function on maps to work just the same
way that indexing usually works on maps.

there are a number of possible workarounds (e.g. write your own
index function, write a "present" function returning whether a key
is present in a map), but it's probably worth raising an issue about.

Andrew Scott

unread,
Aug 1, 2011, 7:17:22 AM8/1/11
to golan...@googlegroups.com
Hi rog

Yeah, for now I've added a function to the FuncMap that I'm using to test the existence of a key in a map.  

If it is really a bug I'll raise an issue but I wasn't sure if there was a more appropriate way todo it.


roger peppe

unread,
Aug 1, 2011, 7:19:27 AM8/1/11
to golan...@googlegroups.com
i've made a CL for this. if you raise an issue, i'll change the CL description
to point to the issue.

Andrew Scott

unread,
Aug 1, 2011, 2:27:36 PM8/1/11
to golan...@googlegroups.com
Oh that's great, many thanks rog

Sorry for the delay, looking to move back into Oxford so I had to go and view some houses.

I'll go raise an issue now.

Andrew Scott

unread,
Aug 1, 2011, 2:41:53 PM8/1/11
to golan...@googlegroups.com
Raised an issue.

But, just seen your commit on "tip", that's fixed it nicely.

Many thanks.

Reply all
Reply to author
Forward
0 new messages