No need to check for nil before a loop

This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

Metadata

ID: go-best-practices/avoid-nil-check-loop

Language: Go

Severity: Info

Category: Best Practices

Description

In Go, if a slice is nil, it is considered empty (with a length of 0). When a for range loop is used on an empty slice, it simply executes zero times. Therefore, it is not necessary to check if the slice s is nil before using it in a for range loop.

Consider the following code snippets:Consider the following code snippets:

func main () {
    if s != nil {
        for _, x := range s {
        
        }
    }
}

In the provided code, the if condition s != nil is checking if s is nil before executing the for range loop. However, this check is not necessary because even if s is nil, the loop will not execute. It is an unnecessary extra check that can be removed to make the code simpler and more readable.

Removing the if condition and directly using the for range loop will not impact the behavior of the code because the loop will simply not execute when s is nil.

Non-Compliant Code Examples

func main () {
    if s != nil {
        for _, x := range s {
        
        }
    }
}

Compliant Code Examples

func main () {
    for _, x := range s {
    
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis