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:
// 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 = "w3wiki" , "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:
"w3wiki" 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
Contact Us