Golang 클로저 - Go series(6)

Date:     Updated:

Categories:

Tags: ,

image

클로저(Closure)

함수는 클로저로서 사용될 수 있다.
클로저란 함수 바깥에 있는 변수를 참조하는 함수값이다.
아래 예제에서 nextValue는 int를 리턴하는 익명함수를 리턴하는 함수인데 바깥에 있는 i를 이용해서 숫자 생성기를 만든 것이다.
마치 함수가 변수를 내부에 유지하고 있는 모양새가 된다.
새로 다른 변수에다가 다시 함수를 할당하게 된다면 그 변수는 다시 0부터 시작하는 클로저가 생기는 것이다.
예제)

package main

func nextValue() func() int{
    i := 0
    return func() int{
        i++
        return i
    }
}

func main(){
    firstClosure = nextValue()
    println(firstClosure()) // 1
    println(firstClosure()) // 2
    println(firstClosure()) // 3
    println(firstClosure()) // 4

    secondClosure = nextValue()
    println(secondClosure()) // 1
    println(secondClosure()) // 2
}

Leave a comment