Compare commits

...

2 commits

Author SHA1 Message Date
e7a7bee8e3 Merge pull request 'docs(blog): clarify %v vs %w in post-6 with examples and AI note' (#2) from develop into main
Reviewed-on: #2
2026-01-12 11:36:30 +00:00
0e67040db4 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.
2026-01-12 20:03:08 +09:00

50
src/blog/post-6.md Normal file
View file

@ -0,0 +1,50 @@
---
title: 'The Difference Between %v and %w in Gos 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.