Control Structures and Functions 🔄

Intermediate

Control flow in Go includes if, for, switch, and select. Unlike some languages, Go uses for as its only looping construct, which can mimic while and do-while loops.

Loop Example

for i := 0; i < 5; i++ {
    fmt.Println(i)
}

Conditional Example

if age >= 18 {
    fmt.Println("Adult")
} else {
    fmt.Println("Minor")
}

Switch Example

switch day {
case "Monday":
    fmt.Println("Start of the week")
case "Friday":
    fmt.Println("Almost weekend")
default:
    fmt.Println("Midweek")
}

Functions

Functions in Go are declared using func. They can return multiple values, which is useful in many scenarios.

func add(a int, b int) int {
    return a + b
}

// Multiple return values
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, fmt.Errorf("division by zero")
    }
    return a / b, nil
}

Functions enhance code reusability and clarity, especially for complex logic.