Skip to content
Open
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
11 changes: 6 additions & 5 deletions env.go
Original file line number Diff line number Diff line change
Expand Up @@ -461,13 +461,14 @@ func doParseSlice(ref reflect.Value, processField processFieldFn, opts Options)
}

sliceType := ref.Type()
initial := ref
var initialized int
if reflect.Pointer == ref.Kind() {
sliceType = sliceType.Elem()
// Due to the rest of code the pre-initialized slice has no chance for this situation
initialized = 0
} else {
initialized = ref.Len()
initial = ref.Elem()
}
if initial.IsValid() {
initialized = initial.Len()
}

var capacity int
Expand All @@ -478,7 +479,7 @@ func doParseSlice(ref reflect.Value, processField processFieldFn, opts Options)
for i := 0; i < capacity; i++ {
item := result.Index(i)
if i < initialized {
item.Set(ref.Index(i))
item.Set(initial.Index(i))
}
if err := doParse(item, processField, optionsWithSliceEnvPrefix(opts, i)); err != nil {
return err
Expand Down
17 changes: 17 additions & 0 deletions slice_pointer_defaults_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package env

import "testing"

func TestSlicePointerPreservesInitialValues(t *testing.T) {
type item struct {
Name string `env:"NAME"`
Port int `env:"PORT"`
}
items := []item{{Name: "first", Port: 8080}, {Name: "second", Port: 9090}}
cfg := struct {
Items *[]item `envPrefix:"ITEMS_"`
}{Items: &items}
err := ParseWithOptions(&cfg, Options{Environment: map[string]string{"ITEMS_0_NAME": "updated"}})
isNoErr(t, err)
isEqual(t, []item{{Name: "updated", Port: 8080}, {Name: "second", Port: 9090}}, *cfg.Items)
}