Generic error vs. module specific error

Hello,

I am currently exploring the SMTP module from github.com/emersion/go-smtp.

So far things work well, but there is one thing I can not wrap my head around.
Certain commands, like Rcpt() are specified to return error but actually return
*SMTPError.

So when I write code that accesses the specific fields and functions of SMTPError,
the compiler tells me that these are undefined, since it expects error.

I don’t even know what to google for. Are there any examples on how to work with
a generic error that’s “overwritten” by a module-specific error? All pointers welcome.

Cheers,
Lordy

1 Like

The Go Programming Language Specification

Type assertions

For an expression x of interface type and a type T, the primary expression

x.(T)

asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion.

A type assertion used in an assignment or initialization of the special form

v, ok = x.(T)
v, ok := x.(T)
var v, ok = x.(T)
var v, ok T1 = x.(T)

yields an additional untyped boolean value. The value of ok is true if the assertion holds. Otherwise it is false and the value of v is the zero value for type T. No run-time panic occurs in this case.

smtpErr, ok := err.(*smtp.SMTPError)
if ok {
    fmt.Println(smtpErr)
}

Take A Tour of Go: Type Assertions

Thank you, @petrus.

Coming from a language like Perl, these things still trip me up.
I am starting to see the advantages of strict typing, but it still has a learning curve.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.