-Go- deferはreturnの前に逆順に実行される。
ここでは当たり前のことを書いてるので許してください。
defer はデストラクタ(←コンストラクタの逆)みたいなもの。
code: Go
package main
import (
"fmt"
)
func helloworld (greeting string) {
fmt.Println("greeting is", greeting)
}
func runHelloworld () string {
defer helloworld("konnichiha!")
helloworld("hello!")
return "GREETING IS DONE!"
}
func main() {
done := runHelloworld()
fmt.Println(done)
}
// 出力
// greeting is hello!
// greeting is konnichiha!
// GREETING IS DONE!
defer はreturn の前に実行されていることがわかる。(当たり前。同じGorutineで実行してるんだからreturnした後に実行はないだろう。jiroshin.icon )
ちなみにdeferがたくさんあった場合の実行順番はこう。
code: Go
package main
import (
"fmt"
)
func helloworld (greeting string) {
fmt.Println("greeting is", greeting)
}
func runHelloworld () string {
helloworld("konnichiha!")
defer helloworld("hello!")
defer helloworld("Janbo!")
defer helloworld("Yeeahh!!")
return "GREETING IS DONE!"
}
func main() {
done := runHelloworld()
fmt.Println(done)
}
// 出力
// greeting is konnichiha!
// greeting is Yeeahh!!
// greeting is Janbo!
// greeting is hello!
// GREETING IS DONE!
deferは逆順に実行されるんだね!
jiroshin.icon なるほどネット!
#golang