Concept Explanation
Reliable Go code handles failure paths as carefully as success paths. In this lesson, you will work with a small function that can fail, return clear errors, and protect the rest of the program from bad input. The focus is not on writing a lot of code, but on making the code honest: validate early, return useful errors, and keep the main flow easy to follow.
Where to Put the Code
- Define color and position variables at the top.
- Create shape drawing or placement logic in the middle.
- Render output (print, canvas, SVG, or styled block) at the end.
Command Reference
- Validate input before doing the main work.
- Return clear errors that explain what failed without exposing unnecessary details.
- Keep success logic and error handling separate enough to scan quickly.
- Test both a normal input and a failure case before you move on.
Step-by-step Guide
- Run the code with a valid input and confirm the expected result.
- Change the input to an invalid value and observe the returned error.
- Add one extra validation rule, such as a minimum length or forbidden value.
- Refactor the function so the failure path is obvious at a glance.
- Finish by checking that every path either returns a value or a useful error.
Practice Exercises
- Update the example so it accepts a username only when it contains letters and numbers.
- Write a second helper that validates an email-like string and returns a clear error on failure.
- Create a version that logs the error in main while keeping validation logic inside its own function.
Coding Challenges
- Handle several invalid input cases without turning the function into a long nested block.
- Design a small input-checking flow that is safe, readable, and easy to extend.
Mini Practice Tasks
- Add one more invalid test case and run it manually.
- Improve one error message so it is easier for a beginner to understand.
- Rename the validation function so its purpose is immediately obvious.
Common Mistake
Mixing x and y axes or using wrong coordinate origin causes shapes to appear in unexpected places.
Real-life Mini Challenge
Draw one square, one triangle, and one circle, then move X marker 2 steps right and 1 step down.