diff --git a/match-some-err-options-results/.gitignore b/match-some-err-options-results/.gitignore new file mode 100644 index 0000000..f0e3bca --- /dev/null +++ b/match-some-err-options-results/.gitignore @@ -0,0 +1,2 @@ +/target +**/*.rs.bk \ No newline at end of file diff --git a/match-some-err-options-results/Cargo.lock b/match-some-err-options-results/Cargo.lock new file mode 100644 index 0000000..0c68409 --- /dev/null +++ b/match-some-err-options-results/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "match-some-err-options-results" +version = "0.1.0" + diff --git a/match-some-err-options-results/Cargo.toml b/match-some-err-options-results/Cargo.toml new file mode 100644 index 0000000..9e845c1 --- /dev/null +++ b/match-some-err-options-results/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "match-some-err-options-results" +version = "0.1.0" +authors = ["Stivenson Rincón "] +edition = "2018" + +[dependencies] diff --git a/match-some-err-options-results/src/main.rs b/match-some-err-options-results/src/main.rs new file mode 100644 index 0000000..db7931b --- /dev/null +++ b/match-some-err-options-results/src/main.rs @@ -0,0 +1,68 @@ +// Return result or None +fn get_slice_or_possible_none(phrase: String) -> Option { + if &phrase == "" { + None + } else { + let first_letters = &phrase[0..2]; + Some(first_letters.to_string()) + } +} + +// Return result or error +fn get_div_or_possible_error(operators: (u32, u32)) -> Result{ + if operators.1 == 0 { + Err("Second operator is zero") + } else { + Ok(operators.0 / operators.1) + } +} + +fn main() { + + // Omit check of possible None + println!("First Letters of Empty string: {:?}",get_slice_or_possible_none("hi! Stivenson".to_string()).unwrap()); + println!("First Letters of string: {:?}",get_slice_or_possible_none("".to_string())); + + + + // Manage possible "None" or successful + let res = get_slice_or_possible_none("hi! Stivenson".to_string()); + match res { + Some(letters) => { + println!("First Letters of string: {:?}", letters); + }, + None => { + println!("Empty String"); + } + } + let res = get_slice_or_possible_none("".to_string()); // overwriting to res + match res { + Some(letters) => { + println!("First Letters of string: {:?}", letters); + }, + None => { + println!("Empty String"); + } + } + + + // Manage possible error or successful + let possible_error = get_div_or_possible_error((10,2)); + match possible_error { + Ok(result_div) => { + println!("Div without error: {:?}", result_div); + }, + Err(message) => { + println!("Div with error: {:?}", message); + } + } + let possible_error = get_div_or_possible_error((10,0)); // overwriting to possible_error + match possible_error { + Ok(result_div) => { + println!("Div without error: {:?}", result_div); + }, + Err(message) => { + println!("Div with error: {:?}", message); + } + } +}