OneBite.Dev - Coding blog in a bite size

format a string in Go

Code snippet on how to format a string in Go

  s := fmt.Sprintf("Hello %s, you owe me %d", "John", 125)

This code uses the fmt (format) package from Go to format a string. First, a variable s is declared and assigned value of the formatting operation which is done using the Sprintf function. The syntax of Sprintf takes two parameters: the first string is a template which contains placeholders %s and %d - these two are placeholders for the two variables that will be supplied into the formatted string. The second parameter is a comma separated list of variables from which values will be picked up and inserted into the template. The variables provided in this example are a string “John” and an integer 125. Finally, the output of the formatting operation is saved in the “s” variable.

go