caarlos0/env

Proposal: add generic `ParseAs`

3timeslazy opened this issue · 2 comments

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?

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