Go 주요 주제

Go Closures and Function Values

Functions are values in Go: store them, pass them, return them, and let them remember variables.

  • 중급
  • 3분 분량
  • 실행 가능한 예제 1개
배울 내용
  • Functions as values
  • Closures keep state
  • Passing a function
next := counter()
1next()
2next()
3next()
count lives on between calls.

A function that remembers

In Go a function is a value: you can store it in a variable, pass it to another function or return it. A closure is a function that keeps using variables from the place where it was created.

counter returns a function that remembers its own count between calls, and each call to counter creates a separate count. apply takes a function as a parameter. The function literal passed to apply reads bonus from main.

핵심 포인트

  1. counter returns a function with its own count.
  2. Each call to counter starts a new count.
  3. A function literal can use variables around it.

실행 가능한 Go 예제

Go
코드 실행 →
main.go
package main

import "fmt"

func counter() func() int {
	count := 0
	return func() int {
		count++
		return count
	}
}

func apply(values []int, transform func(int) int) []int {
	result := make([]int, len(values))
	for i, value := range values {
		result[i] = transform(value)
	}
	return result
}

func main() {
	next := counter()
	fmt.Println(next(), next(), next())

	other := counter() // a separate count
	fmt.Println(other())

	bonus := 10
	fmt.Println(apply([]int{1, 2, 3}, func(n int) int { return n*2 + bonus }))
}
이 예제의 실행 버튼 만들기 코드 실행 결과
1 2 3
1
[12 14 16]

연습

예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.

이 레슨을 마쳤나요?

학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.

다음: JSON Encoding and Decoding →

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지