ट्रैक
/
Go
Go
/
सिलेबस
/
switch शर्तें
sw

switch शर्तें में Go

1 अभ्यास

switch शर्तें के बारे में

switch स्टेटमेंट एक एक्सप्रेशन का मूल्यांकन करता है और ऐसा पहला case चलाता है जो उसकी वैल्यू से मेल खाता है। लंबी if ... else if श्रृंखलाओं से यह अक्सर ज़्यादा साफ़ विकल्प होता है।

बुनियादी उपयोग

operatingSystem := "windows"

switch operatingSystem {
case "windows":
    // do something if the operating system is windows
case "linux":
    // do something if the operating system is linux
case "macos":
    // do something if the operating system is macos
default:
    // do something if the operating system is none of the above
}

कॉमा लगाकर कई वैल्यू एक ही case में रखी जा सकती हैं। अगर एक्सप्रेशन इनमें से किसी एक के बराबर है, तो वह case मेल खाता है:

switch operatingSystem {
case "windows", "linux":
    // do something if the operating system is windows or linux
case "macos":
    // do something if the operating system is macos
default:
    // do something if the operating system is none of the above
}

बिना एक्सप्रेशन वाला switch

switch के बाद लिखा एक्सप्रेशन पूरी तरह छोड़ा भी जा सकता है। तब हर case में एक बूलियन एक्सप्रेशन होता है, और जो पहला एक्सप्रेशन true देता है, वही चलता है।

age := 21

switch {
case age > 20 && age < 30:
    // do something if age is between 20 and 30
case age == 10:
    // do something if age is equal to 10
default:
    // do something else for every other case
}

इनिशियलाइज़ेशन स्टेटमेंट

if की तरह switch में भी एक्सप्रेशन से पहले एक छोटा इनिशियलाइज़ेशन स्टेटमेंट लिखा जा सकता है। वहाँ घोषित वेरिएबलो का स्कोप सिर्फ switch ब्लॉक तक सीमित रहता है:

switch v := getValue(); {
case v < 0:
    // do something if v is less than 0
case v == 0:
    // do something if v is 0
default:
    // do something else for every other case
}
// v will not be accessible here

fallthrough

fallthrough अगले case का कोड तब भी चलाता है, चाहे उसका एक्सप्रेशन मेल खाता हो या नहीं। यह case के कोड की अंतिम स्टेटमेंट होना चाहिए, और उसके बाद चलने के लिए एक और case होना भी ज़रूरी है।

Go के आम कोड में fallthrough कम ही इस्तेमाल होता है, क्योंकि इससे पास-पास वाले case एक-दूसरे पर निर्भर हो जाते हैं। इस वजह से हर case को अलग से समझना मुश्किल हो जाता है और पूरे switch को पढ़ना भी मुश्किल लगता है। जब कई case का व्यवहार एक जैसा होना चाहिए, तो उन्हें कॉमा से जोड़कर एक साथ लिखना ज़्यादा साफ़ रहता है। जब किसी और वजह से कई case में एक ही लॉजिक दोहराया जा रहा हो, तो उस साझा लॉजिक को अलग निकालकर एक हेल्पर फंक्शन में रखने पर विचार कीजिए।

s := "hello"

switch s {
case "hello":
    fmt.Println("hello")
    fallthrough
case "world":
    fmt.Println("world") // also runs, even though s != "world"
}
// Output:
// hello
// world

और जानने के लिए Go by Example: Switch देखिए या Go भाषा का स्पेसिफिकेशन पढ़िए।

GitHub के ज़रिए संपादित करें यह लिंक नई विंडो या टैब में खुलता है।

switch शर्तें सीखिए