caarlos0 / caarlos0/env

Support non‑consecutive indices when parsing slice environment variables

Open Beginner friendly
#435 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
6.3k
Forks
284
Avg merge
1d 17h
Merged PRs (30d)
1

Description

# Brief Description

When faced with slice element environment variables with discontinuous names (e.g., `PREFIX_0`, `PREFIX_2`, `PREFIX_3`), it is impossible to obtain all variable values.

# Current Behavior

Currently, with `PREFIX_0`, `PREFIX_2`, `PREFIX_3`, only `PREFIX_0` is retrieved.

# Expected Behavior

The slice variable should retrieve PREFIX_0, PREFIX_2, and PREFIX_3, and preserve a placeholder (e.g., a zero value) at the missing index 1.

# Steps to Reproduce

```go
type Test struct {
Str string `env:"STR"`
Num int `env:"NUM"`
}
type Config struct {
Foo []Test `envPrefix:"FOO"`
}

os.Setenv("FOO_0_STR", "a")
os.Setenv("FOO_0_NUM", "1")
os.Setenv("FOO_1_STR", "b")
os.Setenv("FOO_1_NUM", "2")
os.Setenv("FOO_3_STR", "d")
os.Setenv("FOO_3_NUM", "4")

var cfg Config
if err := Parse(&cfg); err != nil {
fmt.Println(err)
}
fmt.Printf("%+v\n", cfg)
// Expect: {Foo:[{Str:a Num:1} {Str:b Num:2} {} {Str:d Num:4}]}
// Got: {Foo:[{Str:a Num:1} {Str:b Num:2}}
```

# Root Cause Analysis

`doParseSlice()` does not support discontinuous environment variable index names; it assumes indices are consecutive. For environment variables `PREFIX_0`, `PREFIX_2`, `PREFIX_3`, it finds that `PREFIX_1` does not exist and stops counting. The parser should continue parsing up to the highest index present in the environment variables, preserving gaps between indexes.

https://github.com/caarlos0/env/blob/6c3de6f047c2bab82da5029c23a36e461d8499c9/env.go#L450-L461

Contributor guide

No contributing guide indexed for this repository

Research direction

Start by inspecting doParseSlice() in env.go around lines 450-461 and reproduce the discontinuous-index case from the issue. Done means parsing continues through the highest present index, retains missing positions as zero-value elements, and produces the expected Foo slice with entries at indexes 0, 2, and 3.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
tooling
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Active
Clarity
Clearly specified
Newbie friendliness
84/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.