The Go programming language uses the Errorf
function to generate a customized error message. It supports custom format specifiers and uses a format string to format the output string.
To use this function, you must import the fmt
package in your file and access the Errorf
function within, using the .
notation: fmt.Errorf
.
Here, Errorf
is the actual function, while fmt
is the Go package that stores the definition of this function.
The definition of the Errorf
function inside the fmt
package is as follows:
The fmt.Errorf
function takes two parameters, described below:
format
: This argument is of type string and represents the string containing custom specifiers that the Errorf
uses to format the final output error.
a ...interface{}
: This is the list of all arguments that replace specifier values in the format string to generate the final error message. There can be any number of input arguments and of any type.
The following is a table of the most commonly used format specifiers in Go and their descriptions.
Specifiers | Description |
---|---|
%s |
To print a string |
%d |
To print an integer |
%v |
To print values of all elements in a structure |
%+v |
To print the names and values of all elements in a structure |
The fmt.Errorf
function returns the final error message, generated using the format string and the list of arguments. This output is of type error.
The following example is a simple program. We first initialize a variable with a string and use it with a format string to generate an error message that we then print out using the println
function.
package mainimport ("fmt")func main() {quantity := 500unit := "meters"err := fmt.Errorf("The workshop is less that %d %s",quantity, unit)fmt.Println(err)}
Since the error message that is generated by the Errorf
function is of type error
, you can also use the Error
method to access it. This is shown in the following example:
package mainimport ("fmt")func main() {organization := "Educative"my_err := fmt.Errorf("Hello and welcome to %s", organization)fmt.Println(my_err.Error())}
Free Resources