In this brief article, we will discuss how to use the sprinf function in the Go programming language.
Golang Sprintf Function
The sprinf function is defined in the fmt package. Hence, we need to import it before use. We can do this with a simple import line as:
Once imported, we can use the function. The function syntax is as defined below:
The function takes a formatted string and an interface as the parameter. The function then returns the string without printing it. This means we can save the returned value as a variable.
Sprintf Formatting Specifiers
The sprintf function supports a number of formatting specifiers. The following are some of the common specifiers.
- %d – Print an integer
- %f – Print a float, lowercase.
- %F – Float Uppercase.
- %s – Print a string.
- %o – octal integer.
- %b – binary.
- %X – Hexadecimal, uppercase.
- %x – hexadecimal, lowercase.
- %e – scientific notation, lowercase.
- %E – scientific notation, uppercase.
- %q – quoted character.
- %U – Unicode
- %t = Boolean.
- %p – Pointer address.
Example
Consider the example below:
import (
"fmt"
"io"
"os"
)
funcmain() {
my_str:= "Hello world"
str := fmt.Sprintf("The program say %s\n", my_str)
io.WriteString(os.Stdout, str)
}
The example above uses the sprintf method to format the specified string. You can use other formatting specifiers to format other values.
Conclusion
This short article guides you to working with the sprintf function from the fmt package. Using this function, you can format strings in various ways using the specifiers discussed in this guide.
Thanks for reading.