Skip to content

Proposal: add generic ParseAs #299

@3timeslazy

Description

@3timeslazy

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions