How to use the printf() function in Golang

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.

Syntax

svg viewer
  • 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

Conversion characters tell Golang how to format different data types. Some of the most commonly used specifiers are:

  • v – formats the value in a default format
  • d – formats decimal integers
  • g – formats the floating-point numbers
  • b – formats base 22 numbers
  • o – formats base 88 numbers
  • t – formats true or false values
  • s – formats string values

Code

The following examples show how the printf() function can be used in different situations.

1. Printing a string

The %s conversion character is used in the template string to print string values:

package main
import "fmt"
func main() {
var mystring = "Hello world"
fmt.Printf("The string is %s", mystring)
}

2. Printing a decimal number

The %d conversion character is used in the template string to print integer values:

package main
import "fmt"
func main() {
var mydata int = 64
fmt.Printf("The decimal value is %d", mydata)
}

3. Printing a floating-point number

The %g conversion character is used in the template string to print float values:

package main
import "fmt"
func main() {
var mydata float32 = 3.142
fmt.Printf("The floating point is %g", mydata)
}

4. Printing a binary representation

The %b conversion character is used in the template string to print binary values:

package main
import "fmt"
func main() {
var mydata int = 14
fmt.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.


Copyright ©2024 Educative, Inc. All rights reserved