Skip to content

Commit

Permalink
refactor: exercises to manage of None and Errors
Browse files Browse the repository at this point in the history
- Use of Result and Option 
- Use of Some and None
- Use of Ok and Err
- Use of match
- Use of unwrap
  • Loading branch information
stivenson committed Jun 7, 2019
1 parent a3d2d67 commit 313fa1a
Show file tree
Hide file tree
Showing 4 changed files with 83 additions and 0 deletions.
2 changes: 2 additions & 0 deletions match-some-err-options-results/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/target
**/*.rs.bk
6 changes: 6 additions & 0 deletions match-some-err-options-results/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions match-some-err-options-results/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "match-some-err-options-results"
version = "0.1.0"
authors = ["Stivenson Rincón <stivenson.rpm@gmail.com>"]
edition = "2018"

[dependencies]
68 changes: 68 additions & 0 deletions match-some-err-options-results/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Return result or None
fn get_slice_or_possible_none(phrase: String) -> Option<String> {
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<u32, &'static str>{
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);
}
}
}

0 comments on commit 313fa1a

Please sign in to comment.