AppDividend
Latest Code Tutorials

Golang Sprintf Example | fmt.Sprintf() Function In Go

0

Golang Sprintf is an inbuilt function that formats according to a format specifier and returns the resulting string. 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

Go Sprintf() function is useful to format a string without printing the string.

Syntax

func Sprintf(format string, a ...interface{}) string

Parameters

The function takes a string and the value of which 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 print it, then 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. For this, the standard library provides the packages text/template and html/template.

These packages implement data-driven templates for generating textual output.

The html/template is for generating 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 which are processed and executed when the engine processes the template and generates the output.

You may provide parameters that are included/substituted in the static template and which may 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.

Finally, Golang fmt.Sprintf() function example is over.

See also

Golang String Index()

Golang String ContainsRune()

Golang String EqualFold()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.