Rust की मूल बातें

Rust if, else if and else

Run code only when a condition is true, and use if as an expression that returns a value.

  • शुरुआती
  • 2 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • if, else if, else
  • Conditions must be bool
  • if as an expression
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. The condition must be a bool: Rust does not treat numbers as true or false.

The conditions are checked from top to bottom and only the first true branch runs, so 87 prints Good. Because if is an expression, it can produce a value for let: every branch must then return the same type.

मुख्य बातें

  1. Conditions are checked from top to bottom.
  2. Only the first true branch runs.
  3. let grade = if ... { 'A' } else { 'B' }; stores the result.

चलने योग्य Rust उदाहरण

Rust
कोड चलाएँ →
main.rs
fn main() {
    let score = 87;

    if score >= 90 {
        println!("Excellent");
    } else if score >= 70 {
        println!("Good");
    } else {
        println!("Keep practicing");
    }

    let grade = if score >= 90 { 'A' } else if score >= 80 { 'B' } else { 'C' };
    println!("Grade: {grade}");
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
Good
Grade: B

अभ्यास

उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।

यह पाठ पूरा कर लिया?

अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।

अगला: FizzBuzz →

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज