ADVERTISEMENT
ADVERTISEMENT

Golang fmt.Fprintf() Function with Examples

Golang | fmt.Fprintf() Function: Here, we are going to learn about the Fprintf() function of the fmt package with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 07, 2021

fmt.Fprintf()

In Go language, the fmt package implements formatted I/O with functions analogous to C's printf() and scanf(). The Fprintf() function is an inbuilt function of the fmt package which is used to format according to the given format specifiers and writes to w (io.Writer).

It accepts three parameters (w io.Writer, format string, a ...interface{}) and returns the number of total bytes written and an error if occurred during the write operation.

Syntax:

func Fprintf(
    w io.Writer, 
    format string, 
    a ...interface{}) (n int, err error)

Parameter(s):

  • w : The standard Input/Output.
  • format : String format with the format verbs.
  • 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.Fprintf() 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.Fprintf() function

package main

import (
	"fmt"
	"os"
)

func main() {
	const name, roll = "Alex", 21

	// Formatting error string
	n, err := fmt.Fprintf(os.Stdout,
		"Student %q [Roll: %d] not found\n", name, roll)

	// Printing the bytes written & error
	fmt.Println(n, "Bytes written")
	fmt.Println("Error", err)
}

Output:

Student "Alex" [Roll: 21] not found
36 Bytes written
Error <nil>

Example 2:

// Golang program to demonstrate the
// example of fmt.Fprintf() function

package main

import (
	"fmt"
	"os"
	"time"
)

func main() {
	// Formatting error string
	n, err := fmt.Fprintf(os.Stdout,
		"Error occurred [%d at %v]\n", os.Getpid(), 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]
68 Bytes written
Error <nil>

Golang fmt Package »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.