Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: do not init empty arrays #321

Merged
merged 1 commit into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -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)
}
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
Loading