fmt.Errorf() Function in Golang With Examples
Last Updated :
05 May, 2020
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:
package main
import (
"fmt"
)
func main() {
const name, dept = "GeeksforGeeks" , "CS"
err := fmt.Errorf( "%q is a %q Portal." , name, dept)
fmt.Println(err.Error())
}
|
Output:
"GeeksforGeeks" is a "CS" Portal.
Example 2:
package main
import (
"fmt"
"time"
)
func main() {
err := fmt.Errorf( "error occurred at: %v" , time .Now())
fmt.Println( "An error happened:" , err)
}
|
Output:
An error happened: error occurred at: 2009-11-10 23:00:00 +0000 UTC m=+0.000000001
Share your thoughts in the comments
Please Login to comment...