Skip to content

Commit ec91994

Browse files
AsakuriAonan Zhai
andauthored
fix: preserve nil pointer types in Get() method (#397)
- Changed Get() to return the original nil pointer value instead of untyped nil, preserving the pointer's type information - Added type assertions in TestGetNilPointer to verify the returned nil values maintain their original types (*test, *[]string) Co-authored-by: Aonan Zhai <zhaonan@microsoft.com>
1 parent 99a91c6 commit ec91994

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

koanf.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,7 @@ func (ko *Koanf) Get(path string) any {
357357

358358
// Skil nil pointers before copying.
359359
if rv := reflect.ValueOf(res); rv.Kind() == reflect.Ptr && rv.IsNil() {
360-
return nil
360+
return res
361361
}
362362

363363
out, _ := copystructure.Copy(&res)

tests/koanf_test.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2058,7 +2058,10 @@ func TestGetNilPointer(t *testing.T) {
20582058
var nt *test
20592059
assert.Nil(k.Set("key", nt))
20602060
assert.True(k.Exists("key"))
2061-
assert.Nil(k.Get("key"))
2061+
got := k.Get("key")
2062+
assert.Nil(got)
2063+
_, ok := got.(*test)
2064+
assert.True(ok, "expected type *test, got %T", got)
20622065

20632066
// Test nil value.
20642067
assert.Nil(k.Set("val", nil))
@@ -2067,5 +2070,8 @@ func TestGetNilPointer(t *testing.T) {
20672070
// Test slice.
20682071
var s *[]string
20692072
assert.Nil(k.Set("slice", s))
2070-
assert.Nil(k.Get("slice"))
2073+
gotSlice := k.Get("slice")
2074+
assert.Nil(gotSlice)
2075+
_, ok = gotSlice.(*[]string)
2076+
assert.True(ok, "expected type *[]string, got %T", gotSlice)
20712077
}

0 commit comments

Comments
 (0)