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 3 years have passed since last update.

【Golang】defer(遅延処理)

Posted at

#【Golang】defer(遅延処理)
Golangの基礎学習〜Webアプリケーション作成までの学習を終えたので、復習を兼ねてまとめていく。 基礎〜応用まで。

package main 
//defer 遅延実行
//goroutinやファイルの書き込み、読み込みでよく使われる
//Pythonのwithのよう

import (
	"fmt"
	"os"
)



func main(){
	//
	defer fmt.Println("最後に実行される")
	fmt.Println("最初に実行")

	//3,2,1で実行される
	fmt.Println("run")
	defer fmt.Println(1)
	defer fmt.Println(2)
	defer fmt.Println(3)
	fmt.Println("success")

	//主な使われ方
	//fileを開く
	//_はエラーハンドリング
	file, _ := os.Open("./if.go")
	//最後に閉じる
	defer file.Close()
	//バイト配列作成(文字数)
	data := make([]byte, 100)
	//バイト配列分読み込む
	file.Read(data)
	//文字列に変換して出力
	fmt.Println(string(data))
}
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?