Skip to content

Support any map type in the keys function#482

Open
ricardbejarano wants to merge 1 commit into
Masterminds:masterfrom
bejaratommy:fix-keys-any-map-type
Open

Support any map type in the keys function#482
ricardbejarano wants to merge 1 commit into
Masterminds:masterfrom
bejaratommy:fix-keys-any-map-type

Conversation

@ricardbejarano

Copy link
Copy Markdown

Fixes #455.

Problem

keys was declared as keys(dicts ...map[string]interface{}). Go's text/template reflection can only pass a value to that parameter when it is exactly map[string]interface{}, so calling keys on any other map type failed:

{{ keys .SomeMap }}   # SomeMap is map[string]MyStruct or map[string]int
# error: ... wrong type for value; expected map[string]interface {}; got map[string]...

This is surprising: keys conceptually works on any map.

Fix

keys now accepts ...interface{} and collects the keys reflectively, stringifying each key. dict values (map[string]interface{}) behave exactly as before, so existing templates are unaffected; non-map arguments are skipped rather than causing a hard type error.

Tests

Added TestKeysWithTypedMaps, which exercises keys on map[string]struct{...} and map[string]int through the template engine. The existing TestKeys cases (which cover dict/map[string]interface{}) continue to pass unchanged.

Docs

Updated docs/dicts.md to note that keys accepts any map type, not only dict.

CHANGELOG.md is compiled at release time keyed by the merged PR number, so I've left it untouched.

The keys function was typed as keys(...map[string]interface{}), so Go's
template engine could only pass it dicts of that exact type. Calling keys
on any other map (e.g. map[string]struct{...} or map[string]int) failed
with a type mismatch.

Accept ...interface{} and collect keys reflectively, stringifying each
key. Existing dict (map[string]interface{}) usage is unchanged.

Fixes Masterminds#455
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

keys function does not work with map[string]struct

2 participants