summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--learn_2/Cargo.lock7
-rw-r--r--learn_2/Cargo.toml6
-rw-r--r--learn_2/src/main.rs100
3 files changed, 113 insertions, 0 deletions
diff --git a/learn_2/Cargo.lock b/learn_2/Cargo.lock
new file mode 100644
index 0000000..07c37f4
--- /dev/null
+++ b/learn_2/Cargo.lock
@@ -0,0 +1,7 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "learn_2"
+version = "0.1.0"
diff --git a/learn_2/Cargo.toml b/learn_2/Cargo.toml
new file mode 100644
index 0000000..e32dc2e
--- /dev/null
+++ b/learn_2/Cargo.toml
@@ -0,0 +1,6 @@
+[package]
+name = "learn_2"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
diff --git a/learn_2/src/main.rs b/learn_2/src/main.rs
new file mode 100644
index 0000000..7191e40
--- /dev/null
+++ b/learn_2/src/main.rs
@@ -0,0 +1,100 @@
+struct Library {
+ books: Vec<Book>,
+}
+
+struct Book {
+ title: String,
+ author: String,
+}
+
+impl Library {
+ fn new() -> Self {
+ Self{
+ books: Vec::new(),
+ }
+ }
+
+ fn add(&mut self, book: Book) {
+ // libraries are allowed to have copies of the same book
+ self.books.push(book)
+ }
+
+ fn find(&self, title: &str) -> Option<&Book> {
+ self.books.iter().find(|&x| x.title == title)
+ }
+
+ fn take(&mut self, title: &str) -> Option<Book> {
+ let index = self.books.iter().position(|x| x.title == title)?;
+ Some(self.books.remove(index))
+ }
+
+ fn transfer(&mut self, destination: &mut Library, title: &str) -> bool {
+ if let Some(book) = self.take(title) {
+ destination.add(book);
+ return true;
+ }
+ false
+ }
+}
+
+fn main() {
+ ()
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::*;
+
+ #[test]
+ fn test_new() {
+ let library = Library::new();
+ assert_eq!(library.books.len(), 0);
+ }
+
+ #[test]
+ fn test_add() {
+ let mut library = Library::new();
+ assert_eq!(library.books.len(), 0);
+ library.add(Book{
+ title: String::from("some book"),
+ author: String::from("some author"),
+ });
+ assert_eq!(library.books.len(), 1);
+ }
+
+ #[test]
+ fn test_find() {
+ let mut library = Library::new();
+ library.add(Book{
+ title: String::from("some book"),
+ author: String::from("some author"),
+ });
+ assert!(library.find("some book").is_some());
+ assert!(library.find("other book").is_none());
+ }
+
+ #[test]
+ fn test_take() {
+ let mut library = Library::new();
+ library.add(Book{
+ title: String::from("some book"),
+ author: String::from("some author"),
+ });
+ assert!(library.take("some book").is_some());
+ assert!(library.take("other book").is_none());
+ }
+
+ #[test]
+ fn test_transfer() {
+ let mut library = Library::new();
+ library.add(Book{
+ title: String::from("some book"),
+ author: String::from("some author"),
+ });
+ let mut destination = Library::new();
+ assert!(library.transfer(&mut destination, "some book"));
+ assert!(destination.find("some book").is_some());
+ assert!(library.find("some book").is_none());
+ }
+
+}