Lesson 3 / 7

Control Flow and Functions

if statements

score := 82nif score >= 90 {n    fmt.Println("A")n} else if score >= 75 {n    fmt.Println("B")n} else {n    fmt.Println("C")n}

Notice there are no parentheses around the condition — Go deliberately drops them, and the braces are required even for a single-line body, unlike C or Java where they are optional. This is a small syntax difference, but Go is consistently strict about it across the whole language.

The only loop: for

for i := 0; i < 5; i++ {n    fmt.Println(i)n}nncount := 0nfor count < 3 {          // this is Go's "while" loop -- same for keywordn    count++n}nnfor {                     // infinite loop, exited with breakn    breakn}

Go has exactly one looping keyword, for, used in three different shapes depending on how many of the three parts (init, condition, post) you include. There is no separate while keyword at all — this is a deliberate simplicity choice, not a missing feature.

Functions

func add(a int, b int) int {n    return a + bn}nnfunc divide(a, b float64) (float64, error) {n    if b == 0 {n        return 0, fmt.Errorf("cannot divide by zero")n    }n    return a / b, niln}

Go functions can return multiple values at once — a real, first-class language feature, not a workaround like a tuple or an object. Returning a result alongside an error value, as divide does above, is Go’s standard, idiomatic pattern for signaling that something might go wrong, covered fully in the error handling lesson later in this course.

Named return values

func divide(a, b float64) (result float64, err error) {n    if b == 0 {n        err = fmt.Errorf("cannot divide by zero")n        returnn    }n    result = a / bn    returnn}

Naming the return values up front lets you use a bare return statement, which returns whatever those named variables currently hold — a Go-specific convenience that can make a function’s intent clearer, though many teams prefer the more explicit style from the previous example for anything beyond a very short function.