Last active
April 28, 2023 20:15
-
-
Save pedrovasconcellos/941b86b703453a250cef0c1b19e988e2 to your computer and use it in GitHub Desktop.
Result class in Rust Language
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::HashMap; | |
pub struct ResultT<T> { | |
response: Option<T>, | |
errors: HashMap<String, String>, | |
} | |
impl<T> ResultT<T> { | |
pub fn new() -> Self { | |
ResultT { | |
response: None, | |
errors: HashMap::new(), | |
} | |
} | |
pub fn with_response(response: T) -> Self { | |
ResultT { | |
response: Some(response), | |
errors: HashMap::new(), | |
} | |
} | |
pub fn with_errors(errors: HashMap<String, String>) -> Self { | |
ResultT { | |
response: None, | |
errors, | |
} | |
} | |
pub fn with_response_and_errors(response: T, errors: HashMap<String, String>) -> Self { | |
ResultT { | |
response: Some(response), | |
errors, | |
} | |
} | |
pub fn with_response_and_error(response: T, parameter_error: String, error: String) -> Self { | |
let mut errors = HashMap::new(); | |
errors.insert(parameter_error, error); | |
ResultT { | |
response: Some(response), | |
errors, | |
} | |
} | |
pub fn add_error(mut self, parameter: String, error: String) -> Self { | |
self.errors.insert(parameter, error); | |
self | |
} | |
pub fn contains_error_description(&self, error_description: &str) -> bool { | |
self.errors | |
.values() | |
.any(|v| v == error_description) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment