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
enum
calledMyErrorType
with variants likeNotFound
,UnexpectedError
, andInvalidInput
. - Define a public
CustomError
struct
that contains both aString
message and aMyErrorType
variant. - Implement the necessary traits (
std::fmt::Display
andstd::error::Error
) for yourCustomError
struct so it works with Rust's standard error handling. - Create a public function named
handle_error
that accepts a message and anerror_type
and returns anErr
variant ofResult<(), CustomError>
. - In your
main.rs
, use thehandle_error
function to simulate different errors and demonstrate how to handle them gracefully usingResult
and the?
operator.