if err != nil

Common Patterns and Shortcuts

Handle Go errors by checking `if err != nil` and returning or logging immediately to prevent further execution with invalid data.

Use if err != nil { return err } to immediately exit a function on failure, or if err != nil { log.Fatal(err) } to stop the entire program. This pattern prevents executing code with invalid data and keeps error handling explicit.

func processData() error {
    data, err := readFile("config.txt")
    if err != nil {
        return err
    }
    // Process data safely
    return nil
}

For main functions, use log.Fatal to halt execution:

func main() {
    _, err := connectToDB()
    if err != nil {
        log.Fatal(err)
    }
    // Run application
}