Skip to content

Commit 2683e95

Browse files
authoredAug 7, 2024··
fix: do not init empty arrays (#321)
Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>
1 parent 1282042 commit 2683e95

File tree

3 files changed

+29
-5
lines changed

3 files changed

+29
-5
lines changed
 

‎env.go

+7-5
Original file line numberDiff line numberDiff line change
@@ -416,12 +416,14 @@ func doParseSlice(ref reflect.Value, processField processFieldFn, opts Options)
416416
}
417417
}
418418

419-
if reflect.Ptr == ref.Kind() {
420-
resultPtr := reflect.New(sliceType)
421-
resultPtr.Elem().Set(result)
422-
result = resultPtr
419+
if result.Len() > 0 {
420+
if reflect.Ptr == ref.Kind() {
421+
resultPtr := reflect.New(sliceType)
422+
resultPtr.Elem().Set(result)
423+
result = resultPtr
424+
}
425+
ref.Set(result)
423426
}
424-
ref.Set(result)
425427
}
426428

427429
return nil

‎env_test.go

+20
Original file line numberDiff line numberDiff line change
@@ -2125,3 +2125,23 @@ func TestIssue298ErrorNestedFieldRequiredNotSet(t *testing.T) {
21252125
isErrorWithMessage(t, err, `env: required environment variable "FOO_0_STR" is not set`)
21262126
isTrue(t, errors.Is(err, EnvVarIsNotSetError{}))
21272127
}
2128+
2129+
func TestIssue320(t *testing.T) {
2130+
type Test struct {
2131+
Str string `env:"STR"`
2132+
Num int `env:"NUM"`
2133+
}
2134+
type ComplexConfig struct {
2135+
Foo *[]Test `envPrefix:"FOO_"`
2136+
Bar []Test `envPrefix:"BAR"`
2137+
Baz []Test `env:",init"`
2138+
}
2139+
2140+
cfg := ComplexConfig{}
2141+
2142+
isNoErr(t, Parse(&cfg))
2143+
2144+
isEqual(t, cfg.Foo, nil)
2145+
isEqual(t, cfg.Bar, nil)
2146+
isEqual(t, cfg.Baz, nil)
2147+
}

‎go.mod

+2
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,6 @@ module github.com/caarlos0/env/v11
22

33
retract v11.0.1 // v11.0.1 accidentally introduced a breaking change regarding the behavior of nil pointers. You can now chose to auto-initialize them by setting the `init` tag option.
44

5+
retract v11.2.0 // v11.2.0 accidentally introduced a breaking change regarding the behavior of nil slices of complex types.
6+
57
go 1.18

0 commit comments

Comments
 (0)
Please sign in to comment.