import (
"fmt"
+ "os"
"runtime"
"strings"
)
// - more:true | runtime_test.ExampleFrames.func3
// - more:true | runtime_test.ExampleFrames
}
+
+func ExampleAddCleanup() {
+ tempFile, err := os.CreateTemp(os.TempDir(), "file.*")
+ if err != nil {
+ fmt.Println("failed to create temp file:", err)
+ return
+ }
+
+ ch := make(chan struct{})
+
+ // Attach a cleanup function to the file object.
+ runtime.AddCleanup(&tempFile, func(fileName string) {
+ if err := os.Remove(fileName); err == nil {
+ fmt.Println("temp file has been removed")
+ }
+ ch <- struct{}{}
+ }, tempFile.Name())
+
+ if err := tempFile.Close(); err != nil {
+ fmt.Println("failed to close temp file:", err)
+ return
+ }
+
+ // Run the garbage collector to reclaim unreachable objects
+ // and enqueue their cleanup functions.
+ runtime.GC()
+
+ // Wait until cleanup function is done.
+ <-ch
+
+ // Output:
+ // temp file has been removed
+}