Lessons
Go Introduction
Go Get Started
Go Syntax
Go Comments
Go Variables
- Declare Variables
- Go में Variables का परिचय
- Go में Multiple Variable Declaration
- Variable Naming Rules (नामकरण के नियम)
Go Constants
Go Output
Go Data Types
- Basic Data Types
- Go Boolean Data Type (बूलियन डेटा प्रकार)
- Go Integer Data Types
- Go Float Data Types
- Go String Data Type
Go Arrays
Go Slices
Go Operators
- Go Operators
- Arithmetic Operators
- Assignment Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
Go Conditions
Go Switch
Go Loops
Go Functions
Go Struct
Go Maps
Project Structure
Single-case
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
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