0
0
Goprogramming~5 mins

Return inside loops in Go

Choose your learning style9 modes available
Introduction

Using return inside loops lets you stop the function and give back a result as soon as you find what you need.

When searching for a specific item in a list and you want to stop once found.
When checking conditions in a loop and want to exit early if a condition is met.
When processing data and you want to return a result immediately without finishing the whole loop.
Syntax
Go
for condition {
    if someCheck {
        return value
    }
}

The return statement immediately ends the function, even if inside a loop.

Code after return inside the loop will not run once return is executed.

Examples
This function returns the first even number it finds in the list. It stops looping once it finds one.
Go
func findFirstEven(numbers []int) int {
    for _, num := range numbers {
        if num%2 == 0 {
            return num
        }
    }
    return -1 // if no even number found
}
This function checks if there is any negative number. It returns true immediately when it finds one.
Go
func containsNegative(nums []int) bool {
    for _, n := range nums {
        if n < 0 {
            return true
        }
    }
    return false
}
Sample Program

This program looks for the first positive number in the list. It returns and prints it as soon as it finds it.

Go
package main

import "fmt"

func findFirstPositive(nums []int) int {
    for _, n := range nums {
        if n > 0 {
            return n
        }
    }
    return 0
}

func main() {
    numbers := []int{-3, -2, 0, 4, 5}
    result := findFirstPositive(numbers)
    fmt.Println("First positive number:", result)
}
OutputSuccess
Important Notes

Remember, return ends the whole function, not just the loop.

If you want to skip to the next loop cycle without returning, use continue instead.

Summary

Use return inside loops to stop the function early when you find what you need.

This helps make your code faster by not doing extra work.

Be careful: return ends the whole function, not just the loop.