I am trying to understand the following example
https://gobyexample.com/errors
I understand most of it except for this part:
_, e := f2(42)
if ae, ok := e.(*argError); ok {
fmt.Println(ae.arg)
fmt.Println(ae.prob)
}
I'm not sure what this line does :
if ae, ok := e.(*argError); ok {
e.(*argError)
is a type assertion that casts the value e to *argError type. This is the type f2() returns on error - it is a pointer to an argError struct, which implements the error interface. This type assertion evaluates multi-valued to (ae,ok), where ae is the *argError typed value, if successful, and ok is a boolean letting you know if it was successful.
if statements in go can be separated into an initial assignment part, then a semicolon, then a boolean condition to evaluate to determine the branch.
Altogether, then,
if ae, ok := e.(*argError); ok {
means: try to cast e to *argError, if that is successful (do if block).
Why do this? Because argError has fields that are not in a plain error (arg, prob), and you might want to use those. In real code where you do this, you'd likely also need to handle the case where e was not an argError, but some other error type, in an "else" branch.