To use fmt.Errorf
to create custom error messages with formatted output in Go, you can use the following syntax:
err := fmt.Errorf("Error message with formatted output: %s", variable)
Here's a step-by-step explanation:
fmt.Errorf
function to create a new error, with the error message as the first argument.%s
verb (or any other appropriate verb) in the usual manner.Here's an example:
package main
import (
"fmt"
"strings"
)
func main() {
input := "Hello, World!"
expectedOutput := "welcome to Go."
if !strings.Contains(input, expectedOutput) {
err := fmt.Errorf("Expected output '%s' not found in input: %s", expectedOutput, input)
fmt.Println(err)
}
}
In the example above, the fmt.Errorf
function is used to create a custom error message that includes the expected output and the actual input. The err
variable will contain the formatted error message.
Note: fmt.Errorf
returns an error
type, so you can assign the result to an error
variable or return it from a function.