The fmt.Printf
function in the GO programming language is a function used to print out a formatted string
to the console. fmt.Printf
supports custom format specifiers and uses a format string
to generate the final output string
.
Printf
is the actual function, while fmt
is the GO package that stores the definition of this function. So to use this function, you must import the fmt
package in your file and access the Printf
function within using the .
notation: fmt.Printf
The definition of the Printf
function inside the fmt
package is as follows:
fmt.Printf
first takes the format string as an argument followed by a variable number of arguments.
format
: This argument is of type string
and represents the string containing custom specifiers that the printf
uses to format the final output string
a ...interface{}
: This argument refers to the list of a variable number of arguments that need to be formatted and printed.
The fmt.Printf
function can return two things:
count
: The number of bytes that were written to the standard output.
err
: Any error thrown during the execution of the function.
Following is a table of the most commonly used format specifiers in GO and their descriptions:
Specifiers | Description |
---|---|
%s |
To print a string |
%d |
To print an integer |
%v |
To print values of all elements in a structure |
%+v |
To print the names and values of all elements in a structure |
The following example is a simple program where we print out a single string
along with an integer value:
package mainimport ("fmt")func main() {// declaring variables of different datatypesvar message string = "Hello and welcome to"var year int = 2021// printing out the declared variables following the format stringfmt.Printf("%s educative in %d",message, year)}
This example shows you how you can make use of the return values from the fmt.Printf
function:
package mainimport ("fmt")func main() {// declaring variables of different datatypesvar message string = "Hello and welcome to"var year int = 2021// storing the return values of Printfchar_count, error := fmt.Printf("%s Educative in %d\n",message, year)if error == nil {fmt.Printf("Printf executed without errors!!!\nNumber of characters printed: %d",char_count )}}
Free Resources