Designing a Library

We will learn much more about structs and the Vec<T> type tomorrow. For now, you just need to know part of its API:

  1. fn main() {
  2. let mut vec = vec![10, 20];
  3. vec.push(30);
  4. println!("middle value: {}", vec[vec.len() / 2]);
  5. for item in vec.iter() {
  6. println!("item: {item}");
  7. }
  8. }

Use this to create a library application. Copy the code below to https://play.rust-lang.org/ and update the types to make it compile:

  1. // TODO: remove this when you're done with your implementation.
  2. #![allow(unused_variables, dead_code)]
  3. struct Library {
  4. books: Vec<Book>,
  5. }
  6. struct Book {
  7. title: String,
  8. year: u16,
  9. }
  10. impl Book {
  11. // This is a constructor, used below.
  12. fn new(title: &str, year: u16) -> Book {
  13. Book {
  14. title: String::from(title),
  15. year,
  16. }
  17. }
  18. }
  19. // This makes it possible to print Book values with {}.
  20. impl std::fmt::Display for Book {
  21. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  22. write!(f, "{} ({})", self.title, self.year)
  23. }
  24. }
  25. impl Library {
  26. fn new() -> Library {
  27. unimplemented!()
  28. }
  29. //fn len(self) -> usize {
  30. // unimplemented!()
  31. //}
  32. //fn is_empty(self) -> bool {
  33. // unimplemented!()
  34. //}
  35. //fn add_book(self, book: Book) {
  36. // unimplemented!()
  37. //}
  38. //fn print_books(self) {
  39. // unimplemented!()
  40. //}
  41. //fn oldest_book(self) -> Option<&Book> {
  42. // unimplemented!()
  43. //}
  44. }
  45. // This shows the desired behavior. Uncomment the code below and
  46. // implement the missing methods. You will need to update the
  47. // method signatures, including the "self" parameter! You may
  48. // also need to update the variable bindings within main.
  49. fn main() {
  50. let library = Library::new();
  51. //println!("Our library is empty: {}", library.is_empty());
  52. //
  53. //library.add_book(Book::new("Lord of the Rings", 1954));
  54. //library.add_book(Book::new("Alice's Adventures in Wonderland", 1865));
  55. //
  56. //library.print_books();
  57. //
  58. //match library.oldest_book() {
  59. // Some(book) => println!("My oldest book is {book}"),
  60. // None => println!("My library is empty!"),
  61. //}
  62. //
  63. //println!("Our library has {} books", library.len());
  64. }

Solution