Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "bufio"
- "errors"
- "fmt"
- "log"
- "os"
- )
- type Resource struct {}
- func (r *Resource) Close() {
- fmt.Println("resource closed")
- }
- func initResource(s string) (*Resource, error) {
- if s != "good" {
- return nil, errors.New("this is bad")
- }
- return &Resource{}, nil
- }
- func main() {
- var scanner = bufio.NewScanner(os.Stdin)
- for scanner.Scan() {
- if err := func() error {
- var err error
- resource_1, err := initResource(scanner.Text())
- if err != nil {
- return err
- }
- // say you want to close this resource only if anything that comes after could fail
- defer func() {
- // this is checking for a future error
- if err != nil && resource_1 != nil {
- resource_1.Close()
- }
- }()
- // purposefully fail the scan
- resource_2, err := initResource("s")
- if err != nil {
- // the defer function from earlier is gonna check for this error, therefore closing "resource_1"
- return err
- }
- // you could make a cleanup defer for this resource too if you will initiate others after it
- _ = resource_2
- return nil
- }(); err != nil {
- log.Println(err)
- continue
- }
- }
- }
Advertisement