
Decision Making in GoLang
Decision-making in Go involves executing different code paths based on conditions. It uses control flow statements like if
, else
, switch
, and select
to make decisions.
1. The if
Statement
The if
statement executes a block of code if the condition evaluates to true
.
Syntax:
import "fmt"func main() { age := if condition {
// Code to execute if the condition is true} else { // Code to execute if the condition is false}
Example:
import "fmt"func main() { age := if condition1 {
// Code to execute if condition1 is true} else if condition2 { // Code to execute if condition2 is true} else { // Code to execute if none of the conditions are true}
Example:
import "fmt"func main() { score := switch expression {
case value1: // Code to execute if expression == value1case value2: // Code to execute if expression == value2default: // Code to execute if no case matches}
Example:
import "fmt"func main() { day := 3 switch day { case 1: fmt.Println("Monday") case 2: fmt.Println("Tuesday") case 3: fmt.Println("Wednesday") default: fmt.Println("Invalid day") }}
5. Switch with Multiple Cases
You can group multiple cases for the same block of code.
Example:
func main() { letter := select {case <-channel1: // Code for channel1case <-channel2: // Code for channel2default: // Code if no channel is ready}
Example:
package mainimport ( "fmt" "time")func main() { c1 := func() { time.Sleep(func() { time.Sleep(if variable := expression; condition { // Code to execute}
Example:
package mainimport "fmt"func main() { package mainimport "fmt"func main() { age := 25 employmentStatus := "employed" if age >= 18 && employmentStatus == "employed" { fmt.Println("You are an adult and employed.") } else if age >= 18 { fmt.Println("You are an adult but not employed.") } else { fmt.Println("You are not an adult.") } switch employmentStatus { case "employed": fmt.Println("Keep up the good work!") case "unemployed": fmt.Println("Good luck with the job search!") default: fmt.Println("Employment status unknown.") }}
By mastering decision-making constructs in Go, you can write more efficient, readable, and maintainable code.