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
?
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.