Structs Challenge
To practice what you've learned, let's implement a simple struct for a book in a library. We'll create a Book
struct with a few fields and methods to manage the book's information.
Here is our Book
struct:
Objectives
You are required to implement a few functionalities in the Book
struct:
- Add an associated function called
new()
that creates a new book instance with a default value ofavailable
set totrue
. - Add a
borrow()
method to set theavailable
field tofalse
. - Add a
return_book()
method to set theavailable
field totrue
. - Add a method
is_available()
that returns a boolean indicating if the book is available or not. - Create a few book instances and demonstrate borrow and returning books.
Give it a go by yourself and try not to look at the solution until you've given it a good try. After you finish it or get stuck, you can check the solution below.
Solution
Great job at giving it a try. Let's solve the problem together and see if you got it right.
Step 1: Define the Book
struct
First things first, let's define the Book
struct:
Step 2: Implement the new()
associated function
We need to add a new()
associated function to create a new book instance with a given title and author, and set available
to true
.
Step 3: Implement the borrow()
method
We need to add a borrow()
method to set the available
field to false
.
Step 4: Implement the return_book()
method
We need to add a return_book()
method to set the available
field to true
.
Step 5: Implement the is_available()
method
We need to add a method is_available()
that returns a boolean indicating if the book is available or not.
Step 6: Demonstrate borrowing and returning books
Let's create a few book instances and demonstrate the borrow and returning books methods.
Running the code:
This simple challenge helps you practice basic struct functionalities, including creating instances, mutating fields, and checking conditions.
In the next lesson, we're going to explore how structs work with ownership and borrowing in Rust.