defaults icon indicating copy to clipboard operation
defaults copied to clipboard

tagged defaults

Open willbtlr opened this issue 2 years ago • 4 comments

Hey there! I'd love to be able to set a custom default for a type based on the tag like so:

type Duration struct {
	time.Duration
}

func (d *Duration) SetTaggedDefaults(tag string) (err error) {
	d.Duration, err = time.ParseDuration(tag)
	return
}

type TaggedDefaults struct {
	Duration Duration `default:"1s"`
}

sample := &TaggedDefaults{}
err := Set(sample)
if err != nil { t.Errorf("unexpected error: %s", err) }

if sample.Duration.Duration != time.Second { t.Errorf("expected 1s for Duration, got %s", sample.Duration.Duration) }

This PR adds the interface and modifies the Set() logic to use it. Added tests to account for success and failure. All tests passing. Thanks!

willbtlr avatar May 01 '23 18:05 willbtlr

Ah it looks like IsExported() needs go >= 1.17. I could just check the case of the first char of the field?

willbtlr avatar May 01 '23 18:05 willbtlr

See golang/go#41563, basically you'll want to check if t.Field(i).PkgPath != "" (exported). StructField.PkgPath is populated if and only if the field is unexported.

servusdei2018 avatar Dec 30 '23 15:12 servusdei2018

func (d *Duration) SetTaggedDefaults(tag string) (err error) {

I would utilize https://pkg.go.dev/encoding/json#Unmarshaler or https://pkg.go.dev/encoding#TextUnmarshaler interfaces instead.

creasty avatar Aug 14 '24 11:08 creasty