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 戻り値が関数の時の初期化的な流れ

Posted at

関数が戻り値の時に、どういう流れで初期化されているのか確認してみた

関数を返す前までの準備はされた上で、関数が戻り値として帰る。その戻った関数が実行されるのは、それが実行される時(わかりにくい表現だなぁ)

closure.go
package main                                                                                       

import "fmt"

func intSeq() func() int {
    i := 0
    fmt.Println("init")
    return func() int {
        i += 1
        return i
    }   
}

func main() {
    fmt.Println("before init")
    nextInt := intSeq()
    fmt.Println("after init")

    fmt.Println(nextInt())
    fmt.Println(nextInt())
    fmt.Println(nextInt())
    newInts := intSeq()
    fmt.Println(newInts())
}      

結果

before init
init
after init
1
2
3
init
1
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?