fmt.Errorf() Function in Golang With Examples

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:



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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())
}

chevron_right


Output:

"GeeksforGeeks" is a "CS" Portal.

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
}

chevron_right


Output:

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.