switch case 中的 break 语句在无限循环中不起作用
break statement inside switch case don't have effect in infinite loop
在下面的代码中,我无法理解为什么 default
中的 break
语句不足以结束无限循环。 PlayGroundLink
package main
import "fmt"
func main() {
for { //infinite loop
fmt.Print("Enter Choice")
userChoice := 3 //Intenssionaly given value here for testing
switch userChoice {
case 1:
fmt.Println("Enter Radios of Circle:")
case 2:
fmt.Println("Enter Radios of Circle:")
default:
fmt.Println("\nExiting...")
break // this break is executing , but why it is not coming out of infinte 'for' loop ?
}
}
}
以上代码的输出(未结束..继续)
Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
如果您在循环中添加标签,则可以从循环中显式 break
:
package main
import "fmt"
func main() {
Loop:
for { //infinite loop
fmt.Print("Enter Choice")
userChoice := 3 //Intenssionaly given value here for testing
switch userChoice {
case 1:
fmt.Println("Enter Radios of Circle:")
case 2:
fmt.Println("Enter Radios of Circle:")
default:
fmt.Println("\nExiting...")
break Loop
}
}
fmt.Println("Outside the loop!")
}
在下面的代码中,我无法理解为什么 default
中的 break
语句不足以结束无限循环。 PlayGroundLink
package main
import "fmt"
func main() {
for { //infinite loop
fmt.Print("Enter Choice")
userChoice := 3 //Intenssionaly given value here for testing
switch userChoice {
case 1:
fmt.Println("Enter Radios of Circle:")
case 2:
fmt.Println("Enter Radios of Circle:")
default:
fmt.Println("\nExiting...")
break // this break is executing , but why it is not coming out of infinte 'for' loop ?
}
}
}
以上代码的输出(未结束..继续)
Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
Enter Choice
Exiting...
如果您在循环中添加标签,则可以从循环中显式 break
:
package main
import "fmt"
func main() {
Loop:
for { //infinite loop
fmt.Print("Enter Choice")
userChoice := 3 //Intenssionaly given value here for testing
switch userChoice {
case 1:
fmt.Println("Enter Radios of Circle:")
case 2:
fmt.Println("Enter Radios of Circle:")
default:
fmt.Println("\nExiting...")
break Loop
}
}
fmt.Println("Outside the loop!")
}