The fmt.out.printf()
function in Golang allows users to print formatted data.
The function takes a template string that contains the text that needs to be formatted, plus some annotation verbs that tell the fmt
functions how to format the trailing arguments.
Template string
- the string being passed to the function. It contains the conversion characters which represent objects to be printed.
Object arg
- the object(s) to be printed on the screen.
Conversion characters tell Golang how to format different data types. Some of the most commonly used specifiers are:
The following examples show how the printf()
function can be used in different situations.
The %s
conversion character is used in the template string to print string values:
package mainimport "fmt"func main() {var mystring = "Hello world"fmt.Printf("The string is %s", mystring)}
The %d
conversion character is used in the template string to print integer values:
package mainimport "fmt"func main() {var mydata int = 64fmt.Printf("The decimal value is %d", mydata)}
The %g
conversion character is used in the template string to print float
values:
package mainimport "fmt"func main() {var mydata float32 = 3.142fmt.Printf("The floating point is %g", mydata)}
The %b
conversion character is used in the template string to print binary values:
package mainimport "fmt"func main() {var mydata int = 14fmt.Printf("The binary value of mydata is %b", mydata)}
The above examples demonstrate how we can display our data using various conversion characters. Other data types can also be formatted in the same way using their respective conversion characters, which can be found in the official documentation.
Free Resources