Junior — Senior
Error implemented through the error interface
livecode
Task condition
In the function foo(i int) error, an error of type *MyError is created and returned as a value of the error interface. When checking the result in main(), the message returned by the Error() method is not displayed, although the variable err is not equal to nil. It is necessary to modify the program so that the call to Error() correctly returns the error text and it is displayed in the output.
package main
import "fmt"
type MyError struct {
data string
}
func (e *MyError) Error() string {
return e.data
}
func main() {
err := foo(6)
if err != nil {
fmt.Println("oops:", err)
} else {
fmt.Println("ok")
}
}
func foo(i int) error {
var err error
if i > 5 {
err = &MyError{data: "i > 5"}
}
return err
}