"Go 클로저"의 두 판 사이의 차이

(새 문서: ==개요== ;Go closure ;Go 클로저 <syntaxhighlight lang='go' run> // https://gobyexample.com/closures package main import "fmt" func intSeq() func() int { i := 0 return...)
 
1번째 줄: 1번째 줄:
==개요==
==개요==
;Go closure
;Go closure, Go function closure
;Go 클로저
;Go 클로저, Go 함수 클로저
 
<syntaxhighlight lang='go' run>
// https://tour.golang.org/moretypes/25
package main
 
import "fmt"
 
func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
 
func main() {
pos, neg := adder(), adder()
for i := 0; i < 10; i++ {
fmt.Println(
pos(i),
neg(-2*i),
)
}
}
</syntaxhighlight>


<syntaxhighlight lang='go' run>
<syntaxhighlight lang='go' run>

2021년 10월 20일 (수) 13:16 판

1 개요

Go closure, Go function closure
Go 클로저, Go 함수 클로저
// https://tour.golang.org/moretypes/25
package main

import "fmt"

func adder() func(int) int {
	sum := 0
	return func(x int) int {
		sum += x
		return sum
	}
}

func main() {
	pos, neg := adder(), adder()
	for i := 0; i < 10; i++ {
		fmt.Println(
			pos(i),
			neg(-2*i),
		)
	}
}
// https://gobyexample.com/closures
package main

import "fmt"

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

func main() {

    nextInt := intSeq()

    fmt.Println(nextInt())
    fmt.Println(nextInt())
    fmt.Println(nextInt())

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

2 같이 보기

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}