Open In App

fmt.Errorf() Function in Golang With Examples

Improve
Improve
Like Article
Like
Save
Share
Report

In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Errorf() function in Go language allow us use formatting features to create descriptive error messages. 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 Errorf(format string, a ...interface{}) error

Parameters: This function accepts two parameters which are illustrated below:

  • string: This is your error message with placeholder values such as %s for a string and %d for an integer.
  • a …interface{}: This is either constant variable name used in the code or any inbuilt function.

Return Value: It returns the string as a value that satisfies error.

Example 1:




// Golang program to illustrate the usage of
// fmt.Errorf() function
  
// Including the main package
package main
  
// Importing fmt
import (
    "fmt"
)
  
// Calling main
func main() {
  
    // Declaring some constant variables
    const name, dept = "GeeksforGeeks", "CS"
  
    // Calling the Errorf() function with verb
    // %q which is used for a single-quoted character
    err := fmt.Errorf("%q is a %q Portal.", name, dept)
  
    // Printing the error message
    fmt.Println(err.Error())
}


Output:

"GeeksforGeeks" is a "CS" Portal.

Example 2:




// Golang program to illustrate the usage of
// fmt.Errorf() function
  
// Including the main package
package main
  
// Importing fmt and time
import (
    "fmt"
    "time"
)
  
// Calling main
func main() {
  
    // Calling Errorf() function with verb $v which is used
    // for printing structs
    err := fmt.Errorf("error occurred at: %v", time.Now())
  
    // Printing the error
    fmt.Println("An error happened:", err)
}


Output:

An error happened: error occurred at: 2009-11-10 23:00:00 +0000 UTC m=+0.000000001


Last Updated : 05 May, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads