closures
상태값을 가지는 함수를 반환하는 함수에 대한 예입니다. (출처: https://gobyexample.com)
package main
import (
"fmt"
)
func intSeq() func() int {
i := 0
return func() int {
i += 1
return i
}
}
func main() {
nextInt1 := intSeq()
nextInt2 := intSeq()
fmt.Println(nextInt1())
fmt.Println(nextInt1())
fmt.Println(nextInt1())
fmt.Println(nextInt1())
fmt.Println(nextInt2())
fmt.Println(nextInt2())
fmt.Println(nextInt2())
fmt.Println(nextInt2())
}
결과는 아래와 같습니다.
1 2 3 4 1 2 3 4
가변인자(Variadic)
함수에 임의 개수의 인자를 넘길 수 있는 가변인자를 갖는 함수에 대한 예입니다. 특히 네번째 sum 함수의 호출시 인자를 슬라이스로 전달 가능합니다. (출처: https://gobyexample.com)
package main
import (
"fmt"
)
func sum(nums ...int) {
fmt.Print(nums, " ")
total := 0
for _, num := range nums {
total += num
}
fmt.Println(total)
}
func main() {
sum(1, 2)
sum(1, 2, 3)
sum(1, 2, 3, 4)
nums := []int{1, 2, 3, 4}
sum(nums...)
}
결과는 아래와 같습니다.
[1 2] 3 [1 2 3] 6 [1 2 3 4] 10 [1 2 3 4] 10
