fix: Prevent panic on validating nil pointer to slice field (#252) #253
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This pull request addresses the panic encountered when the
gookit/validate
library attempts to validate a struct that contains a nil pointer to a slice field, as reported in issue #252.Problem:
When validating a struct with a field that is a nil pointer to a slice, the library would panic with an error message:
reflect: call of reflect.Value.Len on zero Value
. This is due to a call toLen()
without first checking if thereflect.Value
is valid and not nil.Solution:
The proposed fix introduces a check that ensures the
reflect.Value
is valid and not nil before any call toLen()
. This prevents the panic by safely handling nil pointers as if they point to empty slices, which aligns with the expected behavior of the validation library.Example:
The issue can be reproduced and tested with the following example:
With the fix applied, the
Validate
method now correctly handles the nil pointer by treating it as an empty slice, and the assertion passes without a panic.