Golang fmt.Errorf() Function with Examples

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

fmt.Errorf()

In Go language, the fmt package implements formatted I/O with functions analogous to C's printf() and scanf(). The Errorf() function is an inbuilt function of the fmt package which is used to format according to a format specifier and returns the string as a value that satisfies error, i.e., the Errorf() function allows us to use formatting features to create descriptive error messages.

It accepts two parameters (format string, a ...interface{}) and returns the formatted string as a value that satisfies the error.

Syntax:

func Errorf(format string, a ...interface{}) error

Parameter(s):

  • format : The string and format verbs (placeholder values) to format the error message.
  • 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.Errorf() function is an error, it returns the formatted string as a value that satisfies the error.

Example 1:

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

package main

import (
	"fmt"
)

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

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

	fmt.Println(err.Error())
}

Output:

Student "Alex" [Roll: 21] not found

Example 2:

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

package main

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

func main() {
	// Format error string with process id & time
	err := fmt.Errorf(
		"Error occurred [%d at %v]",
		os.Getpid(), time.Now())

	fmt.Println(err.Error())
}

Output:

Error occurred [12 at 2009-11-10 23:00:00 +0000 UTC m=+0.000000001]

Golang fmt Package »





Comments and Discussions!

Load comments ↻






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