Exercises
1. Guessing Game
You have to create a simple guessing game which utilizes the knowledge acquired so far.
Firstly, create a new project similar to the one in Lesson 1.
Game Logic:
- Generate a random secret number.
- Prompt the user to guess.
- Read the user's input.
- Compare the guess to the secret number.
- Tell the user if they guessed too high, too low, or correctly.
- Keep looping until the user guesses correctly.
2. Custom Error-Handling System
You will design a custom error-handling system to demonstrate your understanding of Rust's Result, enum, and trait implementation.
Your Task:
- Create a new project with a library module (
src/lib.rs) and a main application file (src/main.rs). - In the library module, define a public
enumcalledMyErrorTypewith variants likeNotFound,UnexpectedError, andInvalidInput. - Define a public
CustomErrorstructthat contains both aStringmessage and aMyErrorTypevariant. - Implement the necessary traits (
std::fmt::Displayandstd::error::Error) for yourCustomErrorstruct so it works with Rust's standard error handling. - Create a public function named
handle_errorthat accepts a message and anerror_typeand returns anErrvariant ofResult<(), CustomError>. - In your
main.rs, use thehandle_errorfunction to simulate different errors and demonstrate how to handle them gracefully usingResultand the?operator.