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

Proposal: add generic ParseAs #299

Closed
3timeslazy opened this issue Apr 1, 2024 · 2 comments · Fixed by #300
Closed

Proposal: add generic ParseAs #299

3timeslazy opened this issue Apr 1, 2024 · 2 comments · Fixed by #300

Comments

@3timeslazy
Copy link

Hi there,

Thank you for your work!

While working with the library I thought what if there was a generic function that returned typed values. Something like that

func ParseAs[T any]() (T, error) {
	var conf T
	err := env.Parse(&conf)
	if err != nil {
		return conf, err
	}
	return conf, nil
}

Then the caller code would be

-- with ParseAs
conf, err := env.ParseAs[MyConfig]()
if err != nil {
	panic(err)
}

-- classic way
conf := MyConfig{}
if err := env.Parse(&conf); err != nil {
	panic(err)
}

I understand that the difference is insignificant in the case above, but in many code bases I worked with it actually would be

// -- Must defined somewhere
func Must[T any](v T, err error) T {
	if err != nil {
		panic(err)
	}
	return v
}

// -- with ParseAs
conf := Must(env.ParseAs[MyConfig]())

// -- classic way
conf := MyConfig{}
if err := env.Parse(&conf); err != nil { // can't use Must
	panic(err)
}

What do you think?

caarlos0 added a commit that referenced this issue Apr 1, 2024
closes #299

Signed-off-by: Carlos Alexandro Becker <[email protected]>
@caarlos0
Copy link
Owner

caarlos0 commented Apr 1, 2024

see #300

@3timeslazy
Copy link
Author

Oh, I was looking for this kind of discussion and was sure there was nothing. Thank you!

caarlos0 added a commit that referenced this issue Apr 2, 2024
* feat: ParseAs, ParseAsWithOptions, Must

closes #299

Signed-off-by: Carlos Alexandro Becker <[email protected]>

* build: build with go 1.17 as well

Signed-off-by: Carlos Alexandro Becker <[email protected]>

* feat: change min go version to 1.18

Signed-off-by: Carlos Alexandro Becker <[email protected]>

---------

Signed-off-by: Carlos Alexandro Becker <[email protected]>
BorzdeG pushed a commit to BorzdeG/env that referenced this issue Aug 24, 2024
* feat: ParseAs, ParseAsWithOptions, Must

closes caarlos0#299

Signed-off-by: Carlos Alexandro Becker <[email protected]>

* build: build with go 1.17 as well

Signed-off-by: Carlos Alexandro Becker <[email protected]>

* feat: change min go version to 1.18

Signed-off-by: Carlos Alexandro Becker <[email protected]>

---------

Signed-off-by: Carlos Alexandro Becker <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants