The fmt
package
Here is a list of features provided by the fmt
package:
- Format things like basic strings and values.
- Print data to the console.
- Collect user input from the console.
- Write into a file using a writer.
- Print error messages.
Templates
The fmt
package relies on the concept of a format template. Essentially, this is only a string that contains the text we want to manage plus some placeholders called verbs that tell fmt the format
and where to insert our variables.
Verbs
There are a lot of verbs that are provided by the fmt
package, including:
%v
is a generic placeholder that we can use when we’re not interested in providing a particular format and the default behavior fits well.%T
prints the provided variable’s type.%d
prints our variable as an integer in base-10.%x
and%X
print our variable in hexadecimal format (base-16).%f
prints a floating point number.%q
prints a quoted string that is a string wrapped within double quotes.%p
prints the pointer address of our variable.
Printing
The primary purpose of this package is to print a formatted output somewhere. Let’s see where we can send our data.
STDOUT
STDOUT simply means the terminal. For printing to the console, some commonly used functions are as follows:
- The
fmt.Print
function prints a list of variables with the default format.
- The
fmt.Printf
function allows us to specify a format template. - The
fmt.Println
function is the same asfmt.Print
except it inserts spaces between the variables and appends a new line at the end.
Get hands-on with 1200+ tech skills courses.