Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for map #1

Open
juzeon opened this issue Mar 11, 2024 · 1 comment
Open

Support for map #1

juzeon opened this issue Mar 11, 2024 · 1 comment

Comments

@juzeon
Copy link

juzeon commented Mar 11, 2024

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!

@juzeon
Copy link
Author

juzeon commented Mar 11, 2024

This library resolves my issue 👍

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

No branches or pull requests

1 participant