docs(blog): clarify %v vs %w in post-6 with examples and AI note #2
1 changed files with 50 additions and 0 deletions
50
src/blog/post-6.md
Normal file
50
src/blog/post-6.md
Normal file
|
|
@ -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.
|
||||
Loading…
Add table
Add a link
Reference in a new issue