0

I have method that looks like this:

var eventNotDetected = errors.New("Event not detected")

type VoucherUsageEvent struct {
    M models.M
}

func detectVoucherUsageEvent(_ uint64, changeset changelog.Changeset) (VoucherUsageEvent, error) {
    var event VoucherUsageEvent

    if changeset.GetHeader().Table != db.TABLE_NAME {
        return event, eventNotDetected
    }

    switch changeset.(type) {
    case changelog.InsertChangeset, changelog.UpdateChangeset:
        m, err := models.Map(changeset)

        if err != nil {
            return event, err
        }

        return VoucherUsageEvent{m}, nil

    default:
        return event, eventNotDetected
    }
}

The idea is that it can return an object instance or not, depending on the input. If the object instance can't be returned, the function should indicate why it could not be returned (error occurred during mapping, or just not found)

The return signature is a bit weird when the function doesn't return the instance, for example:

return event, eventNotDetected
return event, err

Basically I just use event because I can't return just nil.

Or is the better way to just return a reference in this case, so I could change the return cases to:

return nil, eventNotDetected
return nil, err
Max
  • 15,693
  • 14
  • 81
  • 131
  • If the *only* reason you'd be returning a pointer instead of a zero value is because you don't like the return semantics, just return the zero value. The decision between pointer and value shouldn't just be based on how your return statements look. – Adrian Jun 23 '17 at 13:35
  • In the end I returned an interface, which made it possible to return nil and made the pointer go away. – Max Jun 23 '17 at 23:05

1 Answers1

0

Yes you can, define the out parameter as pointer *VoucherUsageEvent.

func detectVoucherUsageEvent(_ uint64, changeset changelog.Changeset) (*VoucherUsageEvent, error)

Return as reference or nil.

return &VoucherUsageEvent{m}, nil

OR

return &event, eventNotDetected

OR

return nil, err
jeevatkm
  • 4,571
  • 1
  • 23
  • 24
  • I'm relatively new to Go, so is this considered good practice/preferred over returning the struct as non-reference? – Max Jun 23 '17 at 03:47
  • Yes it is. Also it's based on your use case; whether you need a return as reference or non-reference. Please refer this [SO post](https://stackoverflow.com/a/23551970) to know more. – jeevatkm Jun 23 '17 at 03:53