What is the Golang function Fprint?
The Fprint function in the Go programming language is used to print out a formatted string to the destination of your choosing. fmt.Fprint does not support custom format specifiers, which means only the default formats are used to format the string.
Here, Fprint 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 Fprint function within by using the . notation: fmt.Fprint.
Function definition
The definition of the Fprint function inside the fmt package is as follows:
Parameters
fmt.Fprint takes a writing destination, along with a list of a variable number of arguments:
dest: The destination where the formatted string is to be printed. This should be an object of typeio.Writer.
io.Writeobjects are, in simple terms, objects that have a built-inwritemethod.
a ...interface{}: The list of all arguments that need to be formatted and printed.
Return values
The fmt.Fprint 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.
Example
The following example is a simple program where we print out a single string and an integer value. First, we print it to 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.Fprint(&temp_buff, message, year)fmt.Print(&temp_buff)}
Now, in this second example, we print out a single 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 Fprint 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 Educative \n"// storing the return values of fprintchar_count, error := fmt.Fprint(os.Stdout, message)if error == nil {fmt.Print("Fprint executed without errors and wrote ",char_count, " characters")}}
Free Resources