Skip to content

feat: support arbitrary slices and arrays in ToSlice - #369

Open
AdamMagued wants to merge 1 commit into
spf13:masterfrom
AdamMagued:feat-toslice-support-arbitrary-slices
Open

AdamMagued wants to merge 1 commit into
spf13:masterfrom
AdamMagued:feat-toslice-support-arbitrary-slices

Conversation

@AdamMagued

Copy link
Copy Markdown

Summary

Fixes #355

Currently, ToSliceE only converts slices that match []any or []map[string]any in its type switch. When provided typed slices (such as []int, []string, or slices of structs) or fixed-size arrays, ToSliceE fails with an error unable to cast to []any.

Technical Root Cause

ToSliceE lacked reflection fallback to decompose arbitrary slice and array types into generic []any elements.

Changes

  • In ToSliceE, check for nil explicitly, then use reflection to handle reflect.Slice and reflect.Array kinds in the default switch branch.
  • Allocate []any with length matching rv.Len() and copy elements using rv.Index(idx).Interface().
  • Add test coverage in TestSlice covering []int, []string, arrays ([3]int, [2]string), and slices of structs.

Verification

  • Ran go test -v .: all tests passed cleanly.
  • Ran go vet .: no violations.

In ToSliceE, only []any and []map[string]any were explicitly handled in the type switch. When callers passed typed slices (such as []int, []string, or slices of custom structs) or fixed-size arrays, ToSliceE returned an error unable to cast to []any.

Use reflection to inspect reflect.Slice and reflect.Array inputs, allocating a []any slice of corresponding length and converting each indexed element via Interface(). Add regression tests covering []int, []string, arrays, and struct slices.

Fixes spf13#355
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

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.

Feature: ToSlice

2 participants