Go cơ bản

Go if, else and switch

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

  • Cơ bản
  • Đọc trong 4 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • 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.

Những điểm quan trọng

  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.

Ví dụ Go chạy được

Go
Chạy code →
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")
	}
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
Good
odd
Grade: B
weekend

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Tiếp theo: FizzBuzz →

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách