-
-
Save RandyMcMillan/93dee284404dc7aa2000eac531a1b547 to your computer and use it in GitHub Desktop.
impl_from_config_error.rs
This file contains hidden or 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
#[allow(dead_code)] | |
#[derive(Debug)] | |
enum ConfigError { | |
MissingKey(String), | |
ParseError(std::num::ParseIntError), | |
} | |
impl From<std::num::ParseIntError> for ConfigError { | |
fn from(err: std::num::ParseIntError) -> Self { | |
ConfigError::ParseError(err) | |
} | |
} | |
fn get_config_good(key: &str) -> Result<String, ConfigError> { | |
let config: std::collections::HashMap<&str, &str> = | |
[("port", "8080")].iter().cloned().collect(); | |
config | |
.get(key) | |
.ok_or_else(|| ConfigError::MissingKey(key.to_string())) | |
.map(|s| s.to_string()) | |
} | |
fn parse_port_good(port: &str) -> Result<u16, ConfigError> { | |
port.parse::<u16>().map_err(ConfigError::from) | |
} | |
fn main() { | |
match get_config_good("port") { | |
Ok(port) => println!("Port: {:?}", &parse_port_good(&port)), | |
Err(e) => eprintln!("Error: {:?}", e), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment