The fmt.Errorf() function is a built-in function in Go that is used to format error messages. It returns an error value that contains the formatted error message.
Here is an example of using fmt.Errorf() to format an error message:
package main
import (
"errors"
"fmt"
)
func divide(x, y int) (int, error) {
if y == 0 {
return 0, fmt.Errorf("Cannot divide %d by zero", x)
}
return x / y, nil
}
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
}
In the above code, the divide()
function takes two integers as input and attempts to divide them. If the second input is zero, it returns an error using fmt.Errorf(). The format string "%d" is used to include the value of 'x' in the error message.
In the main function, the divide()
function is called with arguments 10 and 0. Since dividing by zero is invalid, the divide()
function returns an error. If there is an error, err
will not be nil and the error message can be printed using fmt.Println().
Running this program will output:
Error: Cannot divide 10 by zero
By using fmt.Errorf(), you can easily format error messages with variables or values in Go.