Home >Backend Development >Golang >Interesting Control Flow in the circle
in Go (Golang), control flow is managed using several fundamental constructs, including conditionals (if, else), loops (for), and switch statements. Here's an overview of how these constructs work in Go:
Basic Statement
package main import "fmt" func main() { age := 20 if age >= 18 { fmt.Println("You are an adult.") } }
'if-else statement' Example
`package main
import "fmt"
func main() {
age := 16
if age >= 18 { fmt.Println("You are an adult.") } else { fmt.Println("You are not an adult.") }
}
`
'if-else if-else' Statement:
package main import "fmt" func main() { age := 20 if age >= 21 { fmt.Println("You can drink alcohol.") } else if age >= 18 { fmt.Println("You are an adult, but cannot drink alcohol.") } else { fmt.Println("You are not an adult.") } }
2.Loops: for
Go uses the 'for' loop for all looping needs; it does not have a 'while' or loop
basic 'for' loop:
package main import "fmt" func main() { for i := 0; i < 5; i++ { fmt.Println(i) } }
'for' as a 'while' loop:
package main import "fmt" func main() { i := 0 for i < 5 { fmt.Println(i) i++ } }
Infinite Loop:
package main func main() { for { // This loop will run forever } }
'for' loop with 'range':
This is often used to iterate over slices,arrays,maps or strings.
package main import "fmt" func main() { numbers := []int{1, 2, 3, 4, 5} for index, value := range numbers { fmt.Println("Index:", index, "Value:", value) } }
Basic 'switch'
package main import "fmt" func main() { day := "Monday" switch day { case "Monday": fmt.Println("Start of the work week.") case "Friday": fmt.Println("End of the work week.") default: fmt.Println("Midweek.") } }
Switch with multiple expressions in a case:
package main import "fmt" func main() { day := "Saturday" switch day { case "Saturday", "Sunday": fmt.Println("Weekend!") default: fmt.Println("Weekday.") } }
A switch with no expression acts like a chain of if-else statements.
package main import "fmt" func main() { age := 18 switch { case age < 18: fmt.Println("Underage") case age >= 18 && age < 21: fmt.Println("Young adult") default: fmt.Println("Adult") } }
package main import "fmt" func main() { defer fmt.Println("This is deferred and will run at the end.") fmt.Println("This will run first.") }
Panic And Recover
package main import "fmt" func main() { defer func() { if r := recover(); r != nil { fmt.Println("Recovered from panic:", r) } }() fmt.Println("About to panic!") panic("Something went wrong.") }
The above is the detailed content of Interesting Control Flow in the circle. For more information, please follow other related articles on the PHP Chinese website!