From 44f109fd33239176c2a8febd4811e1dbc87d9c57 Mon Sep 17 00:00:00 2001 From: Dave Henderson Date: Mon, 5 Jun 2017 09:52:01 -0400 Subject: [PATCH] Support maps with interface{} type keys Signed-off-by: Dave Henderson --- encode.go | 7 +++++-- encode_test.go | 11 +++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/encode.go b/encode.go index d905c21a..88ba61ac 100644 --- a/encode.go +++ b/encode.go @@ -265,7 +265,7 @@ 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) } @@ -273,7 +273,10 @@ func (enc *Encoder) eMap(key Key, rv reflect.Value) { // 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 { diff --git a/encode_test.go b/encode_test.go index 673b7b00..e662d5f0 100644 --- a/encode_test.go +++ b/encode_test.go @@ -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},