Golang Sprintf: How to Use fmt.Sprintf() Function In Go
Golang offers excellent support for string formatting in the Sprintf function. Package fmt implements formatted I/O with functions analogous to C’s printf and scanf. The format ‘verbs’ are derived from C’s but are more straightforward.
Golang Sprintf
Golang Sprintf() is a built-in function that formats according to a format specifier and returns the resulting string. The Sprintf() function accepts a string that needs to be formatted and returns the formatted string.
Syntax
func Sprintf(format string, a ...interface{}) string
Parameters
The Sprintf() function takes a string and the value we need to format.
Return Value
The Sprintf() function returns a String and does not print the string. So after storing it in a variable, we can print the string. See the following example.
Example
// hello.go package main import ( "fmt" ) func main() { const name, age = "Krunal", 27 s := fmt.Sprintf("%s is %d years old.\n", name, age) print(s) }
Output
go run hello.go Krunal is 27 years old.
In the above code, we have initialized two variables. We then use the Sprintf() function to format the string without printing and then store it to another variable, and then we have printed that variable.
If you want to format the string without printing it, you can use Sprintf() and other functions like fmt.Sprint() and fmt.Sprintln(). These are analogous to the functions without the starter S letter, but these Sxxx() variants return the output as the string instead of printing them to the standard output. The standard library provides the packages text/template and html/template.
These packages implement data-driven templates for generating textual output.
The html/template generates the HTML output safe against code injection. It provides the same interface as the package text/template and should be used instead of text/template whenever the output is HTML.
Using the template packages requires you to provide the static template in the form of a string value (which may be originating from the file, in which case you only provide a file name), which may contain the static text, and actions that are processed and executed when the engine processes the template and generates the output.
You may provide parameters included/substituted in the static template and control the output generation process. The typical form of such parameters is structs and map values, which may be nested.
So, Golang Sprintf() function formats according to a format specifier and returns the resulting string.
That’s it for this tutorial.