Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created August 20, 2025 11:58
Show Gist options
  • Select an option

  • Save rust-play/19a8ac7a19c93a4ff142c6f338b203e6 to your computer and use it in GitHub Desktop.

Select an option

Save rust-play/19a8ac7a19c93a4ff142c6f338b203e6 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#[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