1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Go】インターフェース(Error)

Last updated at Posted at 2020-03-24

◎ errorインターフェース
fmtパッケージにあり。
Error()メソッドを利用。
エラーの内容・文字列を返してくれる。

使い方
①ストラクト作る(エラーメッセージで必要な要素を設定)
②ストラクトを型にインターフェースのメソッドと同じ名前のメッソドを作る
③インターフェースのメソッドと同じ返り値の型(string)を設定

※エラーメッセージのやりとりはポインタを利用する
(ポインタ使わなかった場合、EOFの値が異なり処理がうまくいかない)


package main

import (
	"fmt"
)

type NoUser_ErrorMessage struct {
	Username string
}


//エラーメッセージ返す用のメソッド作成
func (e *NoUser_ErrorMessage) Error() string {
	return fmt.Sprintf("User Not found: %v", e.Username)
}


func myFunc() error {
	// falseを設定
	is_ok := false
	if is_ok {
		return nil
	}
	return &NoUser_ErrorMessage{Username: "Ken"}
}

func main() {
	if err := myFunc(); err != nil {
		fmt.Println(err)
	}
}

結果

User not found: Ken
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?