Search
 
SCRIPT & CODE EXAMPLE
 

RUST

custom errors rust

use std::fmt;
type Result<T> = std::result::Result<T, DoubleError>;
// Define our error types. These may be customized for our error handling cases.
// Now we will be able to write our own errors, defer to an underlying error
// implementation, or do something in between.
#[derive(Debug, Clone)]struct DoubleError;
// Generation of an error is completely separate from how it is displayed.
// There's no need to be concerned about cluttering complex logic with the display style.
//// Note that we don't store any extra info about the errors. This means we can't state
// which string failed to parse without modifying our types to carry that information.
impl fmt::Display for DoubleError {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    	write!(f, "invalid first item to double")
    }
}

fn double_first(vec: Vec<&str>) -> Result<i32> {
	vec.first()
    	// Change the error to our new type.
        .ok_or(DoubleError)
        .and_then(|s| {
        	s.parse::<i32>()
            	// Update to the new error type here also.
                .map_err(|_| DoubleError)
                .map(|i| 2 * i)
            })
}
fn print(result: Result<i32>) {
	match result {
    	Ok(n) => println!("The first doubled is {}", n),
        Err(e) => println!("Error: {}", e),
    }
}

fn main() {
	let numbers = vec!["42", "93", "18"];
    let empty = vec![];
    let strings = vec!["tofu", "93", "18"];
    print(double_first(numbers));
    print(double_first(empty));
    print(double_first(strings));
}
Comment

PREVIOUS NEXT
Code Example
Rust :: concat string rust 
Rust :: how to make map in rust language 
Rust :: armanriazi•rust•smartpointer•box 
Rust :: rust number squared 
Rust :: where in Rust 
Rust :: rust modulus 
Rust :: How to pass a string literal 
Rust :: rust vec of generics types 
Rust :: rustlang how to edit project names 
Rust :: armanriazi•rust•static 
Rust :: armanriazi•rust•mem•deallocating 
Rust :: armanriazi•rust•interior-mutability•cell 
Rust :: armanriazi•rust•unsafe•function•or•method 
Rust :: rust currying, preset some arguments 
Rust :: armanriazi•rust•trait•object•safe 
Rust :: rust array literal 
Lua :: roblox make a rainbow part 
Lua :: sleep function lua 
Lua :: lua string to number 
Lua :: lua table is empty 
Lua :: lua click button 
Lua :: repeat until lua 
Lua :: lua table unpack 
Lua :: how to split strings into 2 string by space lua 
Lua :: lua call custom function 
Lua :: lua to integer 
Lua :: when do true loop on roblox 
Matlab :: matlab title figure 
Matlab :: matlab function files 
Basic :: vb string to int32 
ADD CONTENT
Topic
Content
Source link
Name
2+2 =