Skip to content

Support for map #1

@juzeon

Description

@juzeon

Hi. Thanks for the handy library first.

Seems the implementation is not working for map at the mo. When I try:

var a []string
m := map[string][]string{
	"k": a,
}
b, _ = json.Marshal(Initialize(m))
fmt.Println(string(b))

I got:

{"k":null}

I have tried to add:

func initializeNils(v reflect.Value) {
	// Dereference pointer(s).
	for v.Kind() == reflect.Ptr && !v.IsNil() {
		v = v.Elem()
	}

	if v.Kind() == reflect.Slice {
		// Initialize a nil slice.
		if v.IsNil() && v.CanSet() {
			v.Set(reflect.MakeSlice(v.Type(), 0, 0))
			return
		}

		// Recursively iterate over slice items.
		for i := 0; i < v.Len(); i++ {
			item := v.Index(i)
			initializeNils(item)
		}
	}

	// Recursively iterate over struct fields.
	if v.Kind() == reflect.Struct {
		for i := 0; i < v.NumField(); i++ {
			field := v.Field(i)
			initializeNils(field)
		}
	}

+	if v.Kind() == reflect.Map {
+		for _, key := range v.MapKeys() {
+			value := v.MapIndex(key)
+			initializeNils(value)
+		}
+	}
}

But with no effect. I debugged to find out that seems in this case value.CanSet() is false because map value is not addressable (reference).

Would be appreciated if anyone can find a solution to this!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions