0
0
Goprogramming~20 mins

Error interface in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding the Error Interface in Go
📖 Scenario: Imagine you are building a simple program that checks if a user is old enough to vote. If the user is too young, the program should return an error message.
🎯 Goal: You will create a custom error using Go's error interface, check the user's age, and print the error message if the user is not old enough.
📋 What You'll Learn
Create a custom error type that implements the Error() method
Write a function checkAge that returns an error if age is less than 18
Call checkAge with a specific age and handle the error
Print the error message if an error occurs
💡 Why This Matters
🌍 Real World
Custom errors help programs give clear messages when something goes wrong, like invalid user input.
💼 Career
Understanding error handling is essential for writing reliable Go programs used in backend services and tools.
Progress0 / 4 steps
1
Create a custom error type
Create a struct called AgeError with a field message of type string.
Go
Hint

Use type AgeError struct { message string } to define the struct.

2
Implement the Error() method
Add a method Error() to AgeError that returns the message field as a string.
Go
Hint

The method signature should be func (e AgeError) Error() string and return e.message.

3
Write the checkAge function
Write a function called checkAge that takes an age of type int and returns an error. If age is less than 18, return an AgeError with the message "Age is less than 18". Otherwise, return nil.
Go
Hint

Use an if statement to check the age and return the custom error or nil.

4
Call checkAge and print the error
In the main function, call checkAge with the value 16. If an error is returned, print the error message using fmt.Println(err).
Go
Hint

Use err := checkAge(16) and then check if err != nil to print the error.