0
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.

【Golang】エラーハンドリング

Posted at

【Golang】エラーハンドリング

Golangの基礎学習〜Webアプリケーション作成までの学習を終えたので、復習を兼ねてまとめていく。 基礎〜応用まで。

package main
//エラーハンドリング
//Goには例外機構がない。
//Goでは関数が複数の戻り値を返す特製を利用して、エラーが発生したかの処理を書ける。

import (
	//"fmt"
	"log"
	"os"
)

func main() {
	file, err := os.Open("./aaaaa.go")
	//もしエラーだったら
	if err != nil {
		//出力して終了
		log.Fatalln("Error!")
	}	
	//遅延でクローズ
	defer file.Close()
	//スライス作成
	data := make([]byte, 100)
	//100バイト分読み込み、スライスに追加
	count, err := file.Read(data)
	//なければエラー
	if err != nil {
		log.Fatalln("Error")
	}
	//文字列に変換して読み込みを表示
	fmt.Println(count, string(data))


	//errが何度も出てくるが、毎回上書きされている点に注意
	//err :=は最低でも左側(ここでいうfile,count)が定義されれば、エラーにならない。


	//Chdir ディレクトリ移動
	//エラーしか返さない場合は再定義はできない
	//:=にすると、再定義になる為エラーになる。
	//errしか返さない場合は、一行に省略できる
	if err = os.Chdir("test"); err != nil {
		log.Fatalln("Error")
	}	file.Close()
}
0
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
0
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?