What is the Golang function Fprintln?
The Fprintln function in the Go programming language is used to print out a formatted string to the destination of your choosing. Fprintln does not support custom format specifiers, which means only the default formats are used to format the string. Fprintln also appends a newline character at the end of the string.
To use this function, you must import the fmt package in your file and access the Fprintln function within using the . notation: fmt.Fprintln. Here, Fprintln is the actual function, while fmt is the Go package that stores the definition of this function.
Function definition
The definition of the Fprintln function inside the fmt package is as follows:
Parameters
dest: The destination where the formatted string is to be printed. This should be an object of typeio.Writer.
io.Writerobjects 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.Fprintln 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.
Examples
In the following example, we use the Fprintln function to print out a single string formatted string (including an integer value), first to a buffer variable of type bytes.Buffer. Then, we use the normal Print function to write the buffer to the standard output.
The
bytesdata type has a built-inwritefunction, making it a compatible argument to send to theFprintlnfunction. To use theBufferdata type, you need to import thebytespackage.
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.Fprintln(&temp_buff, message, year)fmt.Print(&temp_buff)}
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 Fprintln 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 Fprintlnchar_count, error := fmt.Fprintln(os.Stdout, message)if error == nil {fmt.Print("Fprint executed without errors and wrote ",char_count, " characters")}}
Free Resources