Q:

Struct initializer with multiple steps that can fail

I have the following base code:
r1, err := OpenResource()
if err != nil { return err; }
defer r1.Close()

r2, err := OpenResource()
if err != nil { return err; }
defer r2.Close()

r3, err := OpenResource()
if err != nil { return err; }
defer r3.Close()

// Do something with r1, r2, r3
...

I want to wrap this into a struct, with a method DoSomething, which I would call as follows:
s, err := CreateMyStructWithR1R2R3()
if err != nil { return err }
defer s.Close()
s.DoSomethingWithR1R2R3() 

My first approach of implementing this is:
func CreateMyStructWithR1R2R3() (*MyStruct, error) {
  s := MyStruct{}

  r1, err := OpenResource()
  if err != nil { return nil, err; }
  s.r1 = r1

  r2, err := OpenResource()
  if err != nil { r1.Close(); return nil, err; }
  s.r2 = r2

  r3, err := OpenResource()
  if err != nil { r1.Close(); r2.Close(); return nil, err; }
  s.r3 = r3

  return &s
}

func (s *MyStruct) Close() {
   s.r3.Close()
   s.r2.Close()
   s.r1.Close()
}

func (s *MyStruct) DoSomethingWithR1R2R3() { /* ... */ }

However, the Close() calls in the Create() function when an error occurs feel ugly and prone to errors. 
An alternative approach that comes to mind is:
func CreateMyStructWithR1R2R3() (*MyStruct, error) {
  s := MyStruct{}
  success := false

  r1, err := OpenResource()
  if err != nil { return nil, err; }
  defer func() { if !success { r1.Close() } }()
  s.r1 = r1

  r2, err := OpenResource()
  if err != nil { return nil, err; }
  defer func() { if !success { r2.Close() } }()
  s.r2 = r2

  r3, err := OpenResource()
  if err != nil { return nil, err; }
  defer func() { if !success { r3.Close() } }()
  s.r3 = r3

  success = true
  return &s
}

This feels safer and cleaner, but the bool feels ugly, and when the Go formatter comes along, this makes the code quite a bit longer.
Is there a better common pattern of making sure all resources are closed with such a multi-stage initialization?

A:

You can perhaps push the Close calls to *MyStruct's Close:
func (s *MyStruct) Close() {
    if s.r3 != nil {
        s.r3.Close()
    }
    if s.r2 != nil {
        s.r2.Close()
    }
    if s.r1 != nil {
        s.r1.Close()
    }
}

And update the first implementation of CreateMyStructWithR1R2R3 as:
func CreateMyStructWithR1R2R3() (*MyStruct, error) {
  s := MyStruct{}

  r1, err := OpenResource()
  if err != nil { s.Close(); return nil, err; }
  s.r1 = r1

  r2, err := OpenResource()
  if err != nil { s.Close(); return nil, err; }
  s.r2 = r2

  r3, err := OpenResource()
  if err != nil { s.Close(); return nil, err; }
  s.r3 = r3

  return &s
}

