Skip to content

Commit

Permalink
fix: do not init empty arrays (#321)
Browse files Browse the repository at this point in the history
Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>
  • Loading branch information
caarlos0 authored Aug 7, 2024
1 parent 1282042 commit 2683e95
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
12 changes: 7 additions & 5 deletions env.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 20 additions & 0 deletions env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 2683e95

Please sign in to comment.