Pointer, Error

When a constructor returns a pointer -- thus "escaping" the call stack by placing data onto the heap -- the constructor function should also return an error. This allows any calling code to recognize when the pointer may refer to an invalid piece of data.

We saw this in Functional Configuration where NewClient returned both a Client reference and an error value, which may be nil if there was no error during configuration.

func NewObject(options ...Option) (*Object, error) {
    instance := &Object{}

    for _, option := range options {
         if err := option(instance); err != nil {
             return err
         }
    }
    
    return instance, nil
}

Last updated