comprehensive_rust/src/main.rs

90 lines
1.9 KiB
Rust

#![allow(unused_variables, dead_code)]
struct Library<'a> {
books: Vec<&'a Book>,
}
struct Book {
title: String,
year: u16,
}
impl Book {
fn new(title: &str, year: u16) -> Book {
Book {
title: String::from(title),
year,
}
}
}
impl std::fmt::Display for Book {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ({})", self.title, self.year)
}
}
impl Library<'_> {
fn new() -> Library<'static> {
return Library { books: vec![] };
}
fn len(&self) -> usize {
return self.books.len();
}
fn is_empty(&self) -> bool {
return self.books.len() == 0;
}
fn add_book(&mut self, book: &Book) {
self.books.push(book);
}
fn print_books(&self) {
if self.is_empty() {
println!("no books");
return;
}
for book in self.books.iter() {
println!("\"{}\" ({})", book.title, book.year);
}
}
fn oldest_book(&self) -> Option<&'static Book> {
let mut is_set: u8 = 0;
let mut oldest: &Book;
for book in self.books.iter() {
if is_set == 0 {
oldest = book;
is_set = 1;
continue;
}
if oldest.year > book.year {
oldest = book;
}
}
return Some(oldest);
}
}
fn main() {
let library: &mut Library<'_> = &mut Library::new();
println!("our Library is empty: {}", library.is_empty());
library.add_book(&Book::new("Lord of the Rings", 1954));
library.add_book(&Book::new("Alice's Adventures in Wonderland", 1865));
library.print_books();
match library.oldest_book() {
Some(book) => println!("My oldest book is {book}"),
None => println!("my library is empty!"),
}
println!("Our library has {} Books", library.len());
}