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)
I'm very new to Go - my background is in Ruby, where this is straightforward. Is there a simpler way to do this?
fmt.SprintF function returns a string and you can format the string the very same way you would have with fmt.PrintF
1. Simple strings
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 starterS
letter, but theseSxxx()
variants return the result as astring
instead of printing them to the standard output.For example:
The variable
s
will be initialized with the value:Tip: If you just want to concatenate values of different types, you may not automatically need to use
Sprintf()
(which requires a format string) asSprint()
does exactly this. See this example:For concatenating only
string
s, you may also usestrings.Join()
where you can specify a custom separatorstring
(to be placed between the strings to join).Try these on the Go Playground.
2. Complex strings (documents)
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
andhtml/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 packagetext/template
and should be used instead oftext/template
whenever the output is HTML.Using the
template
packages basically requires you to provide a static template in the form of astring
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 andmap
values which may be nested.Example:
For example let's say you want to generate email messages that look like this:
To generate email message bodies like this, you could use the following static template:
And provide data like this for executing it:
Normally output of templates are written to an
io.Writer
, so if you want the result as astring
, create and write to abytes.Buffer
(which implementsio.Writer
). Executing the template and getting the result asstring
:This will result in the expected output:
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: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 implementsio.Writer
):This will write the result directly to
os.Stdout
. Try this on the Go Playground.In your case, you need to use Sprintf() for format string.
func Sprintf(format string, a ...interface{}) string
Sprintf formats according to a format specifier and returns the resulting string.
s := fmt.Sprintf("Good Morning, This is %s and I'm living here from last %d years ", "John", 20)
Your output will be :
Sprintf
Here also is a use of it in the tutorial, "A Tour of Go."