Skip to content

Instantly share code, notes, and snippets.

@RandyMcMillan
Forked from rust-play/playground.rs
Last active August 20, 2025 12:01
Show Gist options
  • Save RandyMcMillan/93dee284404dc7aa2000eac531a1b547 to your computer and use it in GitHub Desktop.
Save RandyMcMillan/93dee284404dc7aa2000eac531a1b547 to your computer and use it in GitHub Desktop.
impl_from_config_error.rs
#[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