I learned the difference between %v and %w through reviewing Go code with the help of an AI generative model.
%v: String representation of a value
err := someFunction()
return fmt.Errorf("failed to do something: %v", err)
This approach simply embeds the error as a string.
As a result, information about the original error is lost, which means it may not be usable with errors.Is() or errors.As() for error inspection.
%w: Wrapping an error
err := someFunction()
return fmt.Errorf("failed to do something: %w", err)
%w is a special format specifier used with fmt.Errorf() to wrap an error. This allows the original error to be retrieved using errors.Unwrap().
The %w verb for wrapping errors was introduced in Go 1.13.
orig := errors.Unwrap(err)
In addition, wrapped errors can be examined using errors.Is() and errors.As().
if errors.Is(err, io.EOF) {
// Handle EOF
}
var pathErr *os.PathError
if errors.As(err, &pathErr) {
// Type assertion succeeded
}
The official documentation is available here.
Note:Note The review and translation were assisted by an AI generative model. The author is responsible for the final content.