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