พื้นฐาน Go

Go if, else and switch

Choose what runs with if and switch, including Go's switch without a value.

  • ระดับเริ่มต้น
  • อ่าน 4 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • if, else if, else
  • if with a short statement
  • switch and default
score = 87
  1. 1score >= 90false, skip
  2. 2score >= 70true
  3. 3"Good"this branch runs

The first true branch runs

An if statement runs a block only when its condition is true. switch compares one value with several cases, or, without a value, picks the first case that is true.

The conditions are checked from top to bottom and only the first true branch runs, so 87 prints Good. An if can declare a variable before its condition, as remainder shows. A case can list several values, and Go does not fall through to the next case.

ประเด็นสำคัญ

  1. Conditions are checked from top to bottom.
  2. switch does not fall through to the next case.
  3. A case can list several values.

ตัวอย่าง Go ที่รันได้

Go
รันโค้ด →
main.go
package main

import "fmt"

func main() {
	score := 87

	if score >= 90 {
		fmt.Println("Excellent")
	} else if score >= 70 {
		fmt.Println("Good")
	} else {
		fmt.Println("Keep practicing")
	}

	if remainder := score % 2; remainder == 0 {
		fmt.Println("even")
	} else {
		fmt.Println("odd")
	}

	switch {
	case score >= 90:
		fmt.Println("Grade: A")
	case score >= 80:
		fmt.Println("Grade: B")
	default:
		fmt.Println("Grade: C")
	}

	switch day := "sat"; day {
	case "sat", "sun":
		fmt.Println("weekend")
	default:
		fmt.Println("weekday")
	}
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
Good
odd
Grade: B
weekend

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: FizzBuzz →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด