Mr. Deepak Verma
Web Developer
Single-case

Learn Go Language by M-Learnify

Go Language

Single-case


Go भाषा में switch Statement

Go भाषा में switch Statement

switch statement का उपयोग तब किया जाता है जब आपको कई कोड ब्लॉकों में से एक को चुनकर चलाना हो।

Go में switch स्टेटमेंट अन्य भाषाओं जैसे C, C++, Java, JavaScript और PHP की तरह ही काम करता है। फर्क यह है कि Go में हर case के बाद break लिखने की आवश्यकता नहीं होती, क्योंकि यह केवल उसी case का कोड चलाता है जो मेल खाता है।

Single-Case switch Syntax

switch expression {
case x:
   // कोड ब्लॉक
case y:
   // कोड ब्लॉक
case z:
   // कोड ब्लॉक
default:
   // कोड ब्लॉक (वैकल्पिक)
}

कैसे काम करता है:

  • Expression का मूल्यांकन (evaluation) एक बार किया जाता है।
  • उसका मान प्रत्येक case से तुलना किया जाता है।
  • जो case मेल खाता है, उसका कोड चलता है।
  • default वैकल्पिक होता है — जब कोई case मेल नहीं खाता तब चलता है।

उदाहरण: Single-Case switch

यह उदाहरण सप्ताह के दिन का नाम दिखाता है:

package main
import ("fmt")

func main() {
  day := 4

  switch day {
  case 1:
    fmt.Println("Monday")
  case 2:
    fmt.Println("Tuesday")
  case 3:
    fmt.Println("Wednesday")
  case 4:
    fmt.Println("Thursday")
  case 5:
    fmt.Println("Friday")
  case 6:
    fmt.Println("Saturday")
  case 7:
    fmt.Println("Sunday")
  }
}

Result:

Thursday
टिप्पणी: Go में switch स्वतः अगले case पर नहीं जाता। इसलिए break की आवश्यकता नहीं होती।

default Keyword

default का उपयोग तब किया जाता है जब कोई भी case मेल नहीं खाता।

package main
import ("fmt")

func main() {
  day := 8

  switch day {
  case 1:
    fmt.Println("Monday")
  case 2:
    fmt.Println("Tuesday")
  case 3:
    fmt.Println("Wednesday")
  case 4:
    fmt.Println("Thursday")
  case 5:
    fmt.Println("Friday")
  case 6:
    fmt.Println("Saturday")
  case 7:
    fmt.Println("Sunday")
  default:
    fmt.Println("Not a weekday")
  }
}

Result:

Not a weekday

टाइप की संगति (Type Consistency)

सभी case वैल्यूज़ का टाइप switch expression के टाइप से मेल खाना चाहिए। अगर टाइप अलग हुआ तो Go compiler error देगा।

चेतावनी: नीचे दिए उदाहरण में एक case का टाइप अलग है, इसलिए compiler error आएगा।
package main
import ("fmt")

func main() {
  a := 3

  switch a {
  case 1:
    fmt.Println("a is one")
  case "b":
    fmt.Println("a is b")
  }
}

Result:

./prog.go:11:2: cannot use "b" (type untyped string) as type int
← Back to Courses
Course Lessons