Home »
Golang »
Golang Reference
Golang fmt.Fprintln() Function with Examples
Golang | fmt.Fprintln() Function: Here, we are going to learn about the Fprintln() function of the fmt package with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 07, 2021
fmt.Fprintln()
In Go language, the fmt package implements formatted I/O with functions analogous to C's printf() and scanf(). The Fprintln() function is an inbuilt function of the fmt package which is used to format using the default formats for its operands and writes to w (io.Writer). The spaces are always added between operands and a newline is appended.
It accepts two parameters (w io.Writer, a ...interface{}) and returns the number of total bytes written and an error if occurred during the write operation.
Syntax:
func Fprintln(w io.Writer, a ...interface{}) (n int, err error)
Parameter(s):
- w : The standard Input/Output.
- a : A custom type that is used to specify a set of one or more method signatures, here we can provide a set of the variables, constants, functions, etc.
Return Value:
The return type of the fmt.Fprintln() function is (n int, err error), it returns the number of total bytes written and an error if occurred during the write operation.
Example 1:
// Golang program to demonstrate the
// example of fmt.Fprintln() function
package main
import (
"fmt"
"os"
)
func main() {
const name, roll = "Alex", 21
// Formatting error string
n, err := fmt.Fprintln(os.Stdout,
"Student ", name, "[Roll: ", roll, "] not found")
// Printing the bytes written & error
fmt.Println(n, "Bytes written")
fmt.Println("Error", err)
}
Output:
Student Alex [Roll: 21 ] not found
37 Bytes written
Error <nil>
Example 2:
// Golang program to demonstrate the
// example of fmt.Fprintln() function
package main
import (
"fmt"
"os"
"time"
)
func main() {
// Formatting error string
n, err := fmt.Fprintln(os.Stdout,
"Error occurred [", os.Getpid(), " at ", time.Now(), "]")
// Printing the bytes written & error
fmt.Println(n, "Bytes written")
fmt.Println("Error", err)
}
Output:
Error occurred [ 11 at 2009-11-10 23:00:00 +0000 UTC m=+0.000000001 ]
72 Bytes written
Error <nil>
Golang fmt Package »