ฟังก์ชัน (Functions) ใน Golang: วิธีสร้างและใช้งานเบื้องต้น
Go Developer•19 ธันวาคม 2567•Go Basics
GoGolangFunctionsProgramming Basics
ฟังก์ชันเป็นหัวใจสำคัญของการเขียนโปรแกรมใน Go
การประกาศฟังก์ชัน
func add(a int, b int) int { return a + b }
Multiple Return Values
Go สามารถคืนค่าจากฟังก์ชันได้หลายค่าพร้อมกัน
func swap(a, b string) (string, string) { return b, a } func main() { x, y := swap("hello", "world") fmt.Println(x, y) // "world hello" }
Variadic Functions
ฟังก์ชันที่รับ Arguments ได้ไม่จำกัดจำนวน
func sum(nums ...int) int { total := 0 for _, num := range nums { total += num } return total } func main() { fmt.Println(sum(1, 2, 3)) // 6 }
สรุป
ฟังก์ชันใน Go มีความยืดหยุ่นสูงและเป็นเครื่องมือพื้นฐานที่ทรงพลังในการสร้างโปรแกรม