Golang เช่นเดียวกับภาษาการเขียนโปรแกรมอื่นๆ ส่วนใหญ่มี คำ สั่งสวิตช์คำสั่ง switch ในGolang ช่วยให้คุณสามารถประเมินตัวแปรหรือนิพจน์ได้หลายกรณี และมักใช้เมื่อเขียนคำสั่ง if-else หลายคำสั่งซึ่งทำให้โค้ดดูไม่สวยงามและซ้ำซาก

ใน Go คำสั่งสวิตช์เป็นคำสั่งการแยกสาขาหลายทิศทางที่มีประสิทธิภาพในการกำหนดทิศทางการดำเนินการตามค่า (หรือประเภท) ของนิพจน์ มีคำสั่งสวิตช์สองประเภทหลักใน Go :
- สวิตช์การแสดงออก
- ประเภทสวิตช์
ตัวอย่างเช่น:
package main
import "fmt"
func main() {
day := 4
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
default:
fmt.Println("Invalid day")
}
}
ไวยากรณ์คำสั่งสลับใน Golang
switch optstatement; optexpression {
case expression1:
// Khối code
case expression2: # Expression Switch
// Khối code
default:
// Khối code
}
switch var := interfaceValue.(type) {
case type1:
// Khối code
case type2: # Type Switch
// Khối code
default:
// Khối code
}
สวิตช์การแสดงออก
Expression Switchจะประเมินนิพจน์และสลับไปที่กรณีตามค่าของนิพจน์นั้น ถ้าไม่ได้ระบุการแสดงออกสวิตช์ จะ ตั้งค่าเริ่มต้นเป็นtrue
ไวยากรณ์
switch optstatement; optexpression {
case expression1:
// Khối code
case expression2:
// Khối code
default:
// Khối code
}
optstatement:คำสั่งเสริม (เช่น การประกาศตัวแปร)
optexpression:นิพจน์เสริม (ถ้าละเว้น ค่าเริ่มต้นจะเป็นtrue )
ตัวอย่างพร้อมคำสั่งเสริม
ที่นี่จะแนะนำคำสั่งเสริมที่ประกาศตัวแปรวัน จากนั้น คำสั่งสวิตช์จะประเมินวันตามกรณีที่แตกต่างกัน
package main
import "fmt"
func main() {
switch day := 4; day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
default:
fmt.Println("Invalid day")
}
}
ผลลัพธ์:
Thursday
ตัวอย่างที่มีนิพจน์เสริม
ถ้าไม่มีการระบุนิพจน์คำสั่งสวิตช์ใน Golangจะถือว่านิพจน์นั้นเป็นจริง สิ่งนี้ช่วยให้เราสามารถใช้เงื่อนไขแบบบูลีนในคำสั่ง case ได้
package main
import "fmt"
func main() {
day := 4
switch {
case day == 1:
fmt.Println("Monday")
case day == 4:
fmt.Println("Thursday")
case day > 5:
fmt.Println("Weekend")
default:
fmt.Println("Invalid day")
}
}
ผลลัพธ์
Thursday
ประเภทสวิตช์
สวิตช์ประเภทใช้ในการแยกสาขาตามชนิดของค่าอินเทอร์เฟซ แทนที่จะเป็นค่าของมัน สิ่งนี้มีประโยชน์อย่างยิ่งเมื่อต้องจัดการกับตัวแปรที่มีประเภทที่ไม่รู้จัก
ไวยากรณ์
switch var := interfaceValue.(type) {
case type1:
// Khối code
case type2:
// Khối code
default:
// Khối code
}
ตัวอย่างเช่น:
ตัวอย่างนี้ใช้ตัวแปร วันเดียวกันแต่รวมอยู่ในinterface{}เพื่อแสดงการแปลงประเภท
package main
import "fmt"
func main() {
var day interface{} = 4
switch v := day.(type) {
case int:
switch v {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
default:
fmt.Println("Invalid day")
}
default:
fmt.Printf("Unknown type: %T\n", v)
}
}
ผลลัพธ์:
Thursday