0
0
Goprogramming~10 mins

Error interface in Go - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare the error interface method.

Go
type error interface {
	[1]() string
}
Drag options to blanks, or click blank then click option'
Aerror
BError()
CErrorString
DError
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase 'error' instead of 'Error' as method name.
Adding parentheses in the method name in the interface declaration.
2fill in blank
medium

Complete the code to implement the error interface for MyError type.

Go
type MyError struct {
	msg string
}

func (e MyError) [1]() string {
	return e.msg
}
Drag options to blanks, or click blank then click option'
AErrorString
Berror
CError
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'error' or 'String' instead of 'Error' as method name.
Forgetting to return a string.
3fill in blank
hard

Fix the error in the function signature to correctly implement the error interface.

Go
func (e *MyError) [1]() string {
	return e.msg
}
Drag options to blanks, or click blank then click option'
AError()
BError
Cerror
DErrorString
Attempts:
3 left
💡 Hint
Common Mistakes
Including parentheses in the method name in the declaration.
Using lowercase method name.
4fill in blank
hard

Fill both blanks to create a function that returns an error interface value.

Go
func NewError(msg string) [1] {
	return &[2]{msg}
}
Drag options to blanks, or click blank then click option'
Aerror
BMyError
Cmsg
Attempts:
3 left
💡 Hint
Common Mistakes
Returning concrete type instead of interface.
Not using pointer to struct.
5fill in blank
hard

Fill all three blanks to check if an error is nil and print its message.

Go
var err [1] = NewError("fail")
if err [2] nil {
	fmt.Println(err.[3]())
}
Drag options to blanks, or click blank then click option'
Aerror
B!=
CError
D*MyError
Attempts:
3 left
💡 Hint
Common Mistakes
Using pointer type instead of interface for error variable.
Using == instead of != to check error.
Calling method with wrong name or missing parentheses.