Is there a simple way to format a string in Go without printing the string?
I can do:
bar := "bar" fmt.Printf("foo: %s", bar)
But I want the formatted string returned rather than printed so I can manipulate it further.
I could also do something like:
s := "foo: " + bar
But this becomes difficult to read when the format string is complex, and cumbersome when one or many of the parts aren't strings and have to be converted first, like
i := 25 s := "foo: " + strconv.Itoa(i)
Is there a simpler way to do this?
To format strings in Go, we use functions including fmt. Printf , fmt. Sprintf , or fmt. Fscanf .
when printing structs, the plus flag (%+v) adds field names. %#v a Go-syntax representation of the value. %T a Go-syntax representation of the type of the value. %% a literal percent sign; consumes no value.
The Go Sprintf method from fmt package serves just this: String Interpolation.
Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d".
Sprintf is what you are looking for.
Example
fmt.Sprintf("foo: %s", bar)
You can also see it in use in the Errors example as part of "A Tour of Go."
return fmt.Sprintf("at %v, %s", e.When, e.What)
For "simple" strings (typically what fits into a line) the simplest solution is using fmt.Sprintf()
and friends (fmt.Sprint()
, fmt.Sprintln()
). These are analogous to the functions without the starter S
letter, but these Sxxx()
variants return the result as a string
instead of printing them to the standard output.
For example:
s := fmt.Sprintf("Hi, my name is %s and I'm %d years old.", "Bob", 23)
The variable s
will be initialized with the value:
Hi, my name is Bob and I'm 23 years old.
Tip: If you just want to concatenate values of different types, you may not automatically need to use Sprintf()
(which requires a format string) as Sprint()
does exactly this. See this example:
i := 23 s := fmt.Sprint("[age:", i, "]") // s will be "[age:23]"
For concatenating only string
s, you may also use strings.Join()
where you can specify a custom separator string
(to be placed between the strings to join).
Try these on the Go Playground.
If the string you're trying to create is more complex (e.g. a multi-line email message), fmt.Sprintf()
becomes less readable and less efficient (especially if you have to do this many times).
For this the standard library provides the packages text/template
and html/template
. These packages implement data-driven templates for generating textual output. html/template
is for generating HTML output safe against code injection. It provides the same interface as package text/template
and should be used instead of text/template
whenever the output is HTML.
Using the template
packages basically requires you to provide a static template in the form of a string
value (which may be originating from a file in which case you only provide the file name) which may contain static text, and actions which are processed and executed when the engine processes the template and generates the output.
You may provide parameters which are included/substituted in the static template and which may control the output generation process. Typical form of such parameters are struct
s and map
values which may be nested.
Example:
For example let's say you want to generate email messages that look like this:
Hi [name]! Your account is ready, your user name is: [user-name] You have the following roles assigned: [role#1], [role#2], ... [role#n]
To generate email message bodies like this, you could use the following static template:
const emailTmpl = `Hi {{.Name}}! Your account is ready, your user name is: {{.UserName}} You have the following roles assigned: {{range $i, $r := .Roles}}{{if $i}}, {{end}}{{.}}{{end}} `
And provide data like this for executing it:
data := map[string]interface{}{ "Name": "Bob", "UserName": "bob92", "Roles": []string{"dbteam", "uiteam", "tester"}, }
Normally output of templates are written to an io.Writer
, so if you want the result as a string
, create and write to a bytes.Buffer
(which implements io.Writer
). Executing the template and getting the result as string
:
t := template.Must(template.New("email").Parse(emailTmpl)) buf := &bytes.Buffer{} if err := t.Execute(buf, data); err != nil { panic(err) } s := buf.String()
This will result in the expected output:
Hi Bob! Your account is ready, your user name is: bob92 You have the following roles assigned: dbteam, uiteam, tester
Try it on the Go Playground.
Also note that since Go 1.10, a newer, faster, more specialized alternative is available to bytes.Buffer
which is: strings.Builder
. Usage is very similar:
builder := &strings.Builder{} if err := t.Execute(builder, data); err != nil { panic(err) } s := builder.String()
Try this one on the Go Playground.
Note: you may also display the result of a template execution if you provide os.Stdout
as the target (which also implements io.Writer
):
t := template.Must(template.New("email").Parse(emailTmpl)) if err := t.Execute(os.Stdout, data); err != nil { panic(err) }
This will write the result directly to os.Stdout
. Try this on the Go Playground.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With