Skip to content
Related Articles

Related Articles

Improve Article

fmt.Fprintf() Function in Golang With Examples

  • Last Updated : 26 Feb, 2021

In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Fprintf() function in Go language formats according to a format specifier and writes to w. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions.
 

Syntax:  

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

Parameters: This function accepts three parameters which are illustrated below- 
 

  • w io.Writer: This is the specified standard input or output.
  • format string: This is containing some strings including verbs.
  • a …interface{}: This is the specified constant variables used in the code.

Return Value: It returns the number of bytes written and any write error encountered.
Example 1:
 

C






// Golang program to illustrate the usage of
// fmt.Fprintf() function
 
// Including the main package
package main
 
// Importing fmt and os
import (
    "fmt"
    "os"
)
 
// Calling main
func main() {
 
    // Declaring some const variables
    const name, dept = "GeeksforGeeks", "CS"
 
    // Calling Fprintf() function which returns
    // "n" as the number of bytes written and
    // "err" as any error ancountered
    n, err := fmt.Fprintf(os.Stdout, "%s is a %s portal.\n",
                                                name, dept)
 
    // Printing the number of bytes written
    fmt.Print(n, " bytes written.\n")
 
    // Printing if any error encountered
    fmt.Print(err)
 
}

Output: 
 

GeeksforGeeks is a CS portal.
30 bytes written.
<nil>

Example 2:
 

C




// Golang program to illustrate the usage of
// fmt.Fprintf() function
 
// Including the main package
package main
 
// Importing fmt and os
import (
    "fmt"
    "os"
)
 
// Calling main
func main() {
 
    // Declaring some const variables
    const num1, num2, num3 = 5, 10, 15
 
    // Calling Fprintf() function which returns
    // "n" as the number of bytes written and
    // "err" as any error encountered
    n, err := fmt.Fprintf(os.Stdout, "%d + %d = %d.\n",
                                      num1, num2, num3)
 
    // Printing the number of bytes written
    fmt.Print(n, " bytes written.\n")
 
    // Printing if any error encountered
    fmt.Print(err)
 
}

Output: 
 

5 + 10 = 15.
13 bytes written.
<nil>

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :