Search code examples
goretry-logic

Populating unexported fields


I'm using this retry logic with a stop https://upgear.io/blog/simple-golang-retry-function/

My code looks like this

type Stop struct {
    error
}

...
if s, ok := err.(Stop); ok {
   return s.error
}
...

I'm trying to get the Stop functionality to work outside the namespace, so I'm doing this

...
return lib.Stop{errors.New("this is an error")}
...

But I'm getting a complication error:

implicit assignment to unexported field error in struct literal of type lib.Stop

How would I populate the Stop with the error when its unexported?

I was thinking that I need change the struct to Error error but then it doesnt work with the err.(Stop)

Any ideas how to do this?


Solution

  • You could change it to a named field Err error and then explicitly add the Error() string method to make Stop implement error:

    
    type Stop struct {
        Msg error
    }
    
    func (s Stop) Error() string {
        return s.Msg.Error()
    }
    

    Alternatively, you could just create a "constructor" func for Stop (which is the general approach for letting outside callers instantiate a struct with unexported fields):

    type Stop struct {
        error
    }
    
    func NewStop(err error) Stop {
        return Stop{err}
    }