Skip to content

lesiw/defers

Folders and files

NameName
Last commit message
Last commit date

Latest commit

801d168 · Dec 23, 2024

History

26 Commits
Oct 25, 2024
Dec 23, 2024
Jun 16, 2024
Aug 21, 2024
Jun 16, 2024
Dec 23, 2024
Aug 21, 2024
Dec 23, 2024
Dec 23, 2024
Aug 21, 2024
Aug 21, 2024
Jun 18, 2024
Jun 18, 2024
Aug 21, 2024

Repository files navigation

lesiw.io/defers

Go Reference

Package defers handles program-wide defers.

Defers are executed when defers.Exit() is called or when an interrupt signal is caught, whichever happens first.

If an interrupt signal is caught, the program will exit with a status of 128 plus the signal number. In the event the signal number cannot be determined, the program will exit with exit status 1.

Example

package main

import (
    "fmt"
    "os"

    "lesiw.io/defers"
)

// Set stop to true to halt the program.
// This forces the Go Playground to send an os.Interrupt.
// Global defers will still run before the program ends.
var stop = false

var success bool

func main() {
    defer defers.Run()
    defers.Add(func() {
        if success {
            fmt.Fprintln(os.Stderr, "The program executed successfully.")
        } else {
            fmt.Fprintln(os.Stderr, "The program was interrupted.")
        }
    })
    fmt.Println("Preparing to send a greeting...")
    if stop {
        select {}
    }
    fmt.Println("Hello world!")
    success = true
}

▶️ Run this example on the Go Playground

Packages

No packages published

Languages