Help us understand the problem. What is going on with this article?

errors.New()とfmt.Errorf()って...

More than 1 year has passed since last update.

何が違うんですか??

error型を返すところは同じです。

  • エラーメッセージを作る時に fmt.Sprintf() を使いたければ
    • errors.New()
  • そうでなければ
    • fmt.Errorf()

という風に使い分ければいいと思います。

error型を返すところは同じ

errors_example.go
package main

import (
    "errors"
    "fmt"
)

func errorByFmtErrorF() error {
    return fmt.Errorf("Error: %s", "dame-desu-yo")
}

func errorByErrorsNew() error {
    return errors.New(fmt.Sprintf("Error: %s", "aki-masen-yo"))
}

/*
func errorByFmtSprintF() error {
    return fmt.Sprintf("Error: %s", "ikema-sen-yo")
}
*/

func main() {
    fmt.Printf("fmt.Errorf: %#v\n", errorByFmtErrorF())
    fmt.Printf("errors.New: %#v\n", errorByErrorsNew())
    //fmt.Printf("fmt.Sprintf: %#v\n", errorByFmtSprintf())
}

実行結果

$ go run errors_example.go
fmt.Errorf: &errors.errorString{s:"Error: dame-desu-yo"}
errors.New: &errors.errorString{s:"Error: aki-masen-yo"}

同じですね。

ちなみに

上のコードのコメントをアンコメントアウトすると

$ go run errors_example.go 
# command-line-arguments
./errors_example.go:17: cannot use fmt.Sprintf("Error: %s", "ikema-sen-yo") (type string) as type error in return argument:
        string does not implement error (missing Error method)
./errors_example.go:23: undefined: errorByFmtSprintf

コンパイルが通りません。

errorByFmtSprintFerror型を返すfunctionなのに
string型を返してるからですね。

エラーメッセージをよく見てみると

string does not implement error (missing Error method)

Errorメソッドを持っていればerror型じゃなくても大丈夫っぽい??

ちゃんと調べて書く

errortypeじゃなくて、interfaceなの?

もしくは、
interface Error実装の一つがtype errorかな?

調べた

The Go Programming Language - Errors

interfaceでした!

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away