×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang fmt.Fprint() Function with Examples

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

fmt.Fprint()

In Go language, the fmt package implements formatted I/O with functions analogous to C's printf() and scanf(). The Fprint() 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). If there is no string then spaces are added between operands.

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 Fprint(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.Fprint() 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.Fprint() function

package main

import (
	"fmt"
	"os"
)

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

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

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

Output:

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

Example 2:

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

package main

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

func main() {
	// Formatting error string
	n, err := fmt.Fprint(os.Stdout,
		"Error occurred [", os.Getpid(), " at ", time.Now(), "]\n")

	// 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 »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.