golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
124.32k stars 17.7k forks source link

proposal: flags: <Type>VarDefault functions #68714

Open dimovnike opened 3 months ago

dimovnike commented 3 months ago

Proposal Details

Implement flag.VarDefault() functions that would take the default value from the variable itself. For example:

var p string = "default value"
flag.StringVarDefault(&p,"flagName", "usage")

should equal to:

var p string = "default value"
flag.StringVar(&p,"flagName", p, "usage")

If approved, I would like to implement this myself.

gabyhelp commented 3 months ago

Related Issues and Documentation

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)

seankhliao commented 3 months ago

This would be a massive expansion of api surface for almost no / negative gain in clarity and length of code.

We'd need to see more concrete justification for this proposal.

dimovnike commented 3 months ago

In my usage I expose structure fields as flags. The structures are offered by external packages and have default values. Here is an example:


// get the config with default values
cfg := package1.NewConfig()

// expose some fields as flags
flag.DurationVar(&cfg.Field1, "config-field1", cfg.Field1, "description")
flag.DurationVar(&cfg.Field2, "config-field2", cfg.Field2, "description")

The problem is that current implementation is prone to copy-paste errors.

Here is a real example: https://github.com/dimovnike/go-jwks-server/blob/master/internal/config/config.go