The Fprintf function in the Go programming language is used to print out a formatted string to the destination of your choosing.
Fprintf is different from the normal Fprint function, as it supports custom format specifiers and uses a format string to generate the final output string. In contrast, in Fprint, only default formats are used to format the string.
In order to use this function, you must import the fmt package in your file and access the Fprintf function within by using the . notation: fmt.Fprintf. Here, Fprintf is the actual function, while fmt is the Go package that stores the definition of this function.
The definition of the Fprintf function inside the fmt package is as follows:
dest: The destination where the formatted string is to be printed. This should be an object of type io.Writer.
io.Writeobjects are, in simple terms, objects that have a built-inwritemethod.
format: This argument is of type string and represents the string containing custom specifiers that the Fprintf uses to format the final output string.
a ...interface{}:The list of all arguments that need to be formatted and printed.
The fmt.Fprintf 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.
The 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 |
In the following example, we print out a single string along with an integer value, in the form of a formatted string. First, we print a buffer variable of type bytes.Buffer, and then use the normal Print function to write the buffer to the standard output.
package mainimport ("fmt""bytes")func main() {// declaring variables of different datatypesvar message string = "Hello and welcome to "var year int = 2021// temporary buffervar temp_buff bytes.Buffer// printing out the declared variables as a single stringfmt.Fprintf(&temp_buff, "%s educative in %d", message, year)fmt.Print(&temp_buff)}
Now, in this second example, we print out a single formatted string along with an integer value directly to the standard output. Here, we also use the return values to print out relevant data for the Fprintf function used.
The standard input/output is defined in the
ospackage, so you need to include that in your file first.
package mainimport ("fmt""os")func main() {// declaring variables of different datatypesvar message string = "Hello and welcome to"var year int = 2021// storing the return values of fprintchar_count, error := fmt.Fprintf(os.Stdout, "%s educative in %d\n", message, year)if error == nil {fmt.Print("Fprintf executed without errors and wrote ",char_count, " characters")}}
Free Resources