From 7e8ee5ed9cad6484e9f13f81731b102ced58402e Mon Sep 17 00:00:00 2001 From: Adam Carpenter Date: Tue, 9 Jul 2019 15:14:04 -0400 Subject: Init. --- rust-book/adder/Cargo.lock | 4 ++ rust-book/adder/Cargo.toml | 7 ++++ rust-book/adder/src/lib.rs | 92 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+) create mode 100755 rust-book/adder/Cargo.lock create mode 100755 rust-book/adder/Cargo.toml create mode 100755 rust-book/adder/src/lib.rs (limited to 'rust-book/adder') diff --git a/rust-book/adder/Cargo.lock b/rust-book/adder/Cargo.lock new file mode 100755 index 0000000..4fb18f9 --- /dev/null +++ b/rust-book/adder/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/rust-book/adder/Cargo.toml b/rust-book/adder/Cargo.toml new file mode 100755 index 0000000..5224ea1 --- /dev/null +++ b/rust-book/adder/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["carpenat"] +edition = "2018" + +[dependencies] diff --git a/rust-book/adder/src/lib.rs b/rust-book/adder/src/lib.rs new file mode 100755 index 0000000..bc79931 --- /dev/null +++ b/rust-book/adder/src/lib.rs @@ -0,0 +1,92 @@ +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_works() -> Result<(), String> { + if 2 + 2 == 4 { + Ok(()) + } + else { + Err(String::from("two plus two does not equal four")) + } + } + + #[test] + fn larger_can_hold_smaller() { + let larger = Rectangle { length: 8, width: 7 }; + let smaller = Rectangle { length: 5, width: 1 }; + + assert!(larger.can_hold(&smaller)); + } + + #[test] + fn smaller_cannot_hold_larger() { + let larger = Rectangle { length: 8, width: 7 }; + let smaller = Rectangle { length: 5, width: 1 }; + + assert!(!smaller.can_hold(&larger)); + } + + #[test] + fn it_adds_two() { + assert_eq!(4, add_two(2)); + } + + #[test] + fn it_wont_add_two() { + assert_ne!(4, add_two(3)); + } + + #[test] + fn greeting_contains_name() { + let result = greeting("adam"); + assert!(result.contains("adam")); + } + + #[test] + #[should_panic(expected = "must be between 1 and 100")] + fn greater_than_100() { + Guess::new(200); + } +} + +#[derive(Debug)] +pub struct Rectangle { + length: u32, + width: u32, +} + +pub struct Guess { + value: i32, +} + +impl Guess { + pub fn new(value: i32) -> Guess { + if value < 1 || value > 100 { + panic!("must be between 1 and 100, not {}", value); + } + //if value < 1 { + // panic!("must be greater than 1, not {}", value); + //} + //else if value > 100 { + // panic!("must be less than 100, not {}", value); + //} + + Guess { value } + } +} + +impl Rectangle { + pub fn can_hold(&self, other: &Rectangle) -> bool { + self.length > other.length && self.width > other.width + } +} + +pub fn add_two(a: i32) -> i32 { + a + 2 +} + +pub fn greeting(name: &str) -> String { + format!("hello {}", name) +} -- cgit v1.2.3