Skip to content

make go helper for "parsed string or fallback value" pattern #20018

Closed

Description

@amalscale

We have this pattern of "parse string S as type T, but return a fallback value V if parsing fails" all over the place for common T types like bool, time.Duration, etc. In case a util helper doesn't exist already, we should make one and make it discoverable.

func defDuration(a string, def time.Duration) time.Duration {
	if a == "" {
		return def
	}
	v, err := time.ParseDuration(a)
	if err != nil {
		return def
	}
	return v
}

Some examples in 5 mins of searching:

Activity

  1. added theissue type on Jun 5, 2026
  2. sfllaw commented on Jun 19, 2026

    @sfllaw
    Contributor

    Thanks to @ibobgunardi for doing the first half in #20022. There are a second set of helpers that need to be pulled into util/def that take in keys to os.Getenv:

    // defaultBool returns the boolean value of the given envvar name, or
    // defVal if unset or not a bool.
    func defaultBool(name string, defVal bool) bool {
    v := os.Getenv(name)
    ret, err := strconv.ParseBool(v)
    if err != nil {
    return defVal
    }
    return ret
    }

  3. sfllaw commented on Jul 18, 2026

    @sfllaw
    Contributor

    Thanks to @nicholasrossi0530 for finishing the second half of this task in #20277.

    I think we can close this as completed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    good first issue

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions