-2

I have source like the following:

type Record struct {
    Message string `json:"message"`
    Service string `json:"service"`
    Success bool   `json:"success"`
    Error   string `json:"error"`
}

func (zp *Zephyr) Write(err ...*error) {

    if len(err) > 0 {
        errPtr := err[0]
        if errPtr != nil && *errPtr != nil {
            // error occurred, set success to false and Error to the error message
            zp.Success = false
            zp.Error = errPtr
        } else {
            zp.Success = true
        }
    }
}

What I don't understand is how can I access the string that is embedded in errPtr?

specialk
  • 13
  • 1
  • Possible duplicate of [Pointers vs. values in parameters and return values](https://stackoverflow.com/questions/23542989/pointers-vs-values-in-parameters-and-return-values) – Tim Martin Nov 30 '17 at 22:30
  • Thanks to all for the down votes, your insightful comments have been most helpful. – specialk Dec 01 '17 at 14:34

1 Answers1

2

First, you likely don't want *error, you most likely just want error; pointers to interfaces are very seldom the correct choice.

Second, there isn't necessarily a string embedded in an error. The definition of error is nothing more than:

type error interface {
        Error() string
}

Meaning if you call the Error() method, it will return a string, but it may be generated every time the method is called; it's not necessarily a string field in the error object.

Most likely, what you want is something like this:

func (zp *Zephyr) Write(err ...error) {

    if len(err) > 0 {
        errPtr := err[0]
        if errPtr != nil {
            // error occurred, set success to false and Error to the error message
            zp.Success = false
            zp.Error = errPtr.Error()
        } else {
            zp.Success = true
        }
    }
}

If you can't change the signature, you just need to dereference the pointer:

zp.Error = (*errPtr).Error()

Playground example here: https://play.golang.org/p/dxT108660l

Errors are also covered in the Go tour.

Adrian
  • 42,911
  • 6
  • 107
  • 99
  • Sorry I wasn't clear - the code above is what I have to work with - so I can't change from *error to error. I have already tried errPtr.Error() and that doesn't work (unresolved reference 'Error') – specialk Dec 01 '17 at 14:15
  • And that's the answer (dereferencing pointers) - thanks a bunch! – specialk Dec 01 '17 at 14:39