Zenn
Open2

あったらいいなGo Linterメモ

じゅっじゅおーじゅっじゅおー

errorをただ一つ返すfunc Func() errorがある場合

as-is

func Hoge() error {
  if err := Func(); err != nil {
      return err
  }
  return nil
}

to-be

func Hoge() error {
    return Func()
}
じゅっじゅおーじゅっじゅおー

https://cs.opensource.google/go/go/+/refs/tags/go1.23.6:src/fmt/errors.go;l=12-52

If the format specifier includes a %w verb with an error operand, the returned error will implement an Unwrap method returning the operand. If there is more than one %w verb, the returned error will implement an Unwrap method returning a []error containing all the %w operands in the order they appear in the arguments. It is invalid to supply the %w verb with an operand that does not implement the error interface. The %w verb is otherwise a synonym for %v.

エラーはformatで %w 使うとUnwrapで取り出せるようになるぞ
ミスって %w 指定したら %v に変えてくれるぞ

as-is

if err != nil {
    return fmt.Errorf("failed to xxxx: %v", err)
}

to-be

if err != nil {
    return fmt.Errorf("failed to xxxx: %w", err)
}
ログインするとコメントできます