From 2683e95c82982e589af0ddfaad99f6c33abd4fb2 Mon Sep 17 00:00:00 2001 From: Carlos Alexandro Becker Date: Wed, 7 Aug 2024 09:18:23 -0300 Subject: [PATCH] fix: do not init empty arrays (#321) Signed-off-by: Carlos Alexandro Becker --- env.go | 12 +++++++----- env_test.go | 20 ++++++++++++++++++++ go.mod | 2 ++ 3 files changed, 29 insertions(+), 5 deletions(-) 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 e17d474..1a567b4 100644 --- a/env_test.go +++ b/env_test.go @@ -2125,3 +2125,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