หัวข้อสำคัญของ Go
Go Closures and Function Values
Functions are values in Go: store them, pass them, return them, and let them remember variables.
สิ่งที่คุณจะได้เรียนรู้
- Functions as values
- Closures keep state
- Passing a function
next := counter()
1next()
2next()
3next()
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.
ประเด็นสำคัญ
- counter returns a function with its own count.
- Each call to counter starts a new count.
- A function literal can use variables around it.
ตัวอย่าง 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]ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- เรียงลำดับตามคีย์ที่เลือก เรียงคนตามชื่อหรืออายุด้วยตัวเปรียบเทียบที่เลือกได้ขณะรันไทม์ โดยจัดการกรณีเสมอกันอย่างสม่ำเสมอ. ง่าย
- ผู้ติดตามอีเวนต์ ส่งอีเวนต์ไปยังผู้ติดตามของแต่ละหัวข้อแบบ observer แล้วนับว่าแต่ละคนได้รับกี่ครั้ง ง่าย