From 27015152ec769aeed2ab92533772b97c0ef96b11 Mon Sep 17 00:00:00 2001 From: James Fennell Date: Mon, 5 Apr 2021 18:21:59 +0000 Subject: [PATCH] flag: use strings.Builder instead of concatenating strings There is a single function in the flag package whose implementation uses string concatenation instead of the recommended strings.Builder. The function was last touched before strings.Builder was introduced in Go 1.10, which explains the old style code. This PR updates the implementation. Fixes #45392 Change-Id: Id2d8f1788765a0c4faaeb1e6870914f72b3c8442 GitHub-Last-Rev: 0e12fe304593afc627fc4f1597670efd354809b0 GitHub-Pull-Request: golang/go#45393 Reviewed-on: https://go-review.googlesource.com/c/go/+/307329 Run-TryBot: Ian Lance Taylor TryBot-Result: Go Bot Reviewed-by: Ian Lance Taylor Trust: Josh Bleecher Snyder --- src/flag/flag.go | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/flag/flag.go b/src/flag/flag.go index f7598a6758..885a4c8369 100644 --- a/src/flag/flag.go +++ b/src/flag/flag.go @@ -508,31 +508,33 @@ func UnquoteUsage(flag *Flag) (name string, usage string) { // documentation for the global function PrintDefaults for more information. func (f *FlagSet) PrintDefaults() { f.VisitAll(func(flag *Flag) { - s := fmt.Sprintf(" -%s", flag.Name) // Two spaces before -; see next two comments. + var b strings.Builder + fmt.Fprintf(&b, " -%s", flag.Name) // Two spaces before -; see next two comments. name, usage := UnquoteUsage(flag) if len(name) > 0 { - s += " " + name + b.WriteString(" ") + b.WriteString(name) } // Boolean flags of one ASCII letter are so common we // treat them specially, putting their usage on the same line. - if len(s) <= 4 { // space, space, '-', 'x'. - s += "\t" + if b.Len() <= 4 { // space, space, '-', 'x'. + b.WriteString("\t") } else { // Four spaces before the tab triggers good alignment // for both 4- and 8-space tab stops. - s += "\n \t" + b.WriteString("\n \t") } - s += strings.ReplaceAll(usage, "\n", "\n \t") + b.WriteString(strings.ReplaceAll(usage, "\n", "\n \t")) if !isZeroValue(flag, flag.DefValue) { if _, ok := flag.Value.(*stringValue); ok { // put quotes on the value - s += fmt.Sprintf(" (default %q)", flag.DefValue) + fmt.Fprintf(&b, " (default %q)", flag.DefValue) } else { - s += fmt.Sprintf(" (default %v)", flag.DefValue) + fmt.Fprintf(&b, " (default %v)", flag.DefValue) } } - fmt.Fprint(f.Output(), s, "\n") + fmt.Fprint(f.Output(), b.String(), "\n") }) }