diff --git a/env.go b/env.go index 9585321..5b0be18 100644 --- a/env.go +++ b/env.go @@ -416,12 +416,14 @@ func doParseSlice(ref reflect.Value, processField processFieldFn, opts Options) } } - if reflect.Ptr == ref.Kind() { - resultPtr := reflect.New(sliceType) - resultPtr.Elem().Set(result) - result = resultPtr + if result.Len() > 0 { + if reflect.Ptr == ref.Kind() { + resultPtr := reflect.New(sliceType) + resultPtr.Elem().Set(result) + result = resultPtr + } + ref.Set(result) } - ref.Set(result) } return nil diff --git a/env_test.go b/env_test.go index a24e2e1..d1efd6e 100644 --- a/env_test.go +++ b/env_test.go @@ -2215,3 +2215,23 @@ func TestIssue298ErrorNestedFieldRequiredNotSet(t *testing.T) { isErrorWithMessage(t, err, `env: required environment variable "FOO_0_STR" is not set`) isTrue(t, errors.Is(err, EnvVarIsNotSetError{})) } + +func TestIssue320(t *testing.T) { + type Test struct { + Str string `env:"STR"` + Num int `env:"NUM"` + } + type ComplexConfig struct { + Foo *[]Test `envPrefix:"FOO_"` + Bar []Test `envPrefix:"BAR"` + Baz []Test `env:",init"` + } + + cfg := ComplexConfig{} + + isNoErr(t, Parse(&cfg)) + + isEqual(t, cfg.Foo, nil) + isEqual(t, cfg.Bar, nil) + isEqual(t, cfg.Baz, nil) +} diff --git a/go.mod b/go.mod index 215c28b..affcbd4 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,6 @@ module github.com/caarlos0/env/v11 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. +retract v11.2.0 // v11.2.0 accidentally introduced a breaking change regarding the behavior of nil slices of complex types. + go 1.18