diff --git a/25-validation_types/Cargo.toml b/25-validation_types/Cargo.toml new file mode 100644 index 0000000..ae5788f --- /dev/null +++ b/25-validation_types/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "validation_types" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/25-validation_types/src/lib.rs b/25-validation_types/src/lib.rs new file mode 100644 index 0000000..ebad156 --- /dev/null +++ b/25-validation_types/src/lib.rs @@ -0,0 +1,41 @@ +// This is our type to enforce some rules +// Since struct itself is public and word inside of it private +// we're able to create TahinliWord everywhere but +// can't modify it's value (word) outside of this module +// This will allow us to apply some rules +pub struct TahinliWord { + word: String, +} + +impl TahinliWord { + // This's basically a validator that enforces TahinliWord rules + // Since this is private I'm only using it in this module for clean code + fn validator(word: &String) -> bool { + match word.as_str() { + "Tahinli" | "tahinli" | "TAHINLI" => true, + _ => false, + } + } + + // This is one and only function that allow user to create new TahinliWord + // Thanks to this situation we're able to check whatever we want + pub fn new(word: String) -> Self { + TahinliWord::validator(&word); + TahinliWord { word } + } + + // This is a getter method that only exposes it's value + pub fn get(&self) -> &String { + &self.word + } + + // This is a setter method that's the only way to edit existing TahinliWord + // This gives us power to do whatever check we want + pub fn set(&mut self, word: String) { + if TahinliWord::validator(&word) { + self.word = word; + } else { + panic!("\"{}\" is not a Tahinli Word", word); + } + } +} diff --git a/25-validation_types/src/main.rs b/25-validation_types/src/main.rs new file mode 100644 index 0000000..b3ae6e8 --- /dev/null +++ b/25-validation_types/src/main.rs @@ -0,0 +1,19 @@ +use validation_types::TahinliWord; + +fn main() { + println!("Hello, world!"); + + // This will create new TahinliWord type + let mut tahinli_word = TahinliWord::new("Tahinli".to_string()); + // This will print like normal string + println!("{}", tahinli_word.get()); + + // Borrow checker not allow to manipulate it + // It's read only value + // let mut try_to_manipulate = tahinli_word.get(); + // try_to_manipulate.clear(); + + // This will try to bypass Tahinli Word rules and panic + tahinli_word.set("This is not a Tahinli Word".to_string()); + println!("Code won't run this line :/"); +}