Skip to content

Commit

Permalink
Support maps with interface{} type keys
Browse files Browse the repository at this point in the history
Signed-off-by: Dave Henderson <[email protected]>
  • Loading branch information
hairyhenderson committed Jun 5, 2017
1 parent b26d9c3 commit 44f109f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
7 changes: 5 additions & 2 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,15 +265,18 @@ func (enc *Encoder) eMapOrStruct(key Key, rv reflect.Value) {

func (enc *Encoder) eMap(key Key, rv reflect.Value) {
rt := rv.Type()
if rt.Key().Kind() != reflect.String {
if rt.Key().Kind() != reflect.String && rt.Key().Kind() != reflect.Interface {
encPanic(errNonString)
}

// Sort keys so that we have deterministic output. And write keys directly
// underneath this key first, before writing sub-structs or sub-maps.
var mapKeysDirect, mapKeysSub []string
for _, mapKey := range rv.MapKeys() {
k := mapKey.String()
k, ok := mapKey.Interface().(string)
if !ok {
encPanic(errNonString)
}
if typeIsHash(tomlTypeOfGo(rv.MapIndex(mapKey))) {
mapKeysSub = append(mapKeysSub, k)
} else {
Expand Down
11 changes: 11 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,17 @@ ArrayOfMixedSlices = [[1, 2], ["a", "b"]]
},
wantOutput: "b = 1\n\n[a]\n Int = 2\n",
},
"map with interface{} key type": {
input: map[interface{}]interface{}{
"a": map[interface{}]interface{}{"b": 1},
"c": 2,
},
wantOutput: "c = 2\n\n[a]\n b = 1\n",
},
"(error) map with interface{} key type, with non-string key": {
input: map[interface{}]string{true: ""},
wantError: errNonString,
},
"nested map": {
input: map[string]map[string]int{
"a": {"b": 1},
Expand Down

0 comments on commit 44f109f

Please sign in to comment.