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 रिव्यू के साथ।

सभी चैलेंज