From 0e67040db4a03db3885c4418cdf0e83ceca6403c Mon Sep 17 00:00:00 2001 From: Daisuke Date: Mon, 12 Jan 2026 20:03:08 +0900 Subject: [PATCH] docs(blog): clarify %v vs %w in post-6 with examples and AI note Normalize heading levels, add a %v example and explanation, include errors.Unwrap()/errors.Is()/errors.As() examples, and note that the %w verb was introduced in Go 1.13; also correct wording to use errors.Unwrap() and append a bilingual authorship/AI-assistance notice. --- src/blog/post-6.md | 50 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/blog/post-6.md diff --git a/src/blog/post-6.md b/src/blog/post-6.md new file mode 100644 index 0000000..6272d21 --- /dev/null +++ b/src/blog/post-6.md @@ -0,0 +1,50 @@ +--- +title: 'The Difference Between %v and %w in Go’s fmt.Errorf' +pubDate: 2026-01-12 +author: 'Nakahara Daisuke' +tags: ["Go"] +--- + +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 + +```go +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 + +```go +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](https://go.dev/doc/go1.13). + +```go +orig := errors.Unwrap(err) +``` +In addition, wrapped errors can be examined using `errors.Is()` and `errors.As()`. + +```go +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](https://pkg.go.dev/fmt#Errorf). + +--- + +> **Note**:Note The review and translation were assisted by an AI generative model. The author is responsible for the final content. -- 2.49.1