Skip to content

Instantly share code, notes, and snippets.

@mkomitee
Last active August 29, 2015 14:21
Show Gist options
  • Save mkomitee/6a04a75c4d54a3368aa2 to your computer and use it in GitHub Desktop.
Save mkomitee/6a04a75c4d54a3368aa2 to your computer and use it in GitHub Desktop.
wat now?
// My objective is to return an environment variable parsed as an integer,
// and if either the environment variable isn't set, or it can't be parsed as
// an integer, return a default value.
// This works, but is kind of ugly ...
fn u32_from_env_with_default(env: &str, default: u32) -> u32 {
let tmp_1 = std::env::var(env);
if tmp_1.is_ok() {
let tmp_2 = tmp_1.unwrap().parse::<u32>();
if tmp_2.is_ok() {
tmp_2.unwrap()
} else {
default
}
} else {
default
}
}
// While this doesn't work, ... but is there a way to do it somewhat like this?
fn u32_from_env_with_default(env: &str, default: u32) -> u32 {
std::env::var(env).and_then(|v| v.parse::<u32>()).unwrap_or(default)
}
// src/main.rs:63:37: 63:53 error: mismatched types:
// expected `core::result::Result<_, std::env::VarError>`,
// found `core::result::Result<u32, core::num::ParseIntError>`
// (expected enum `std::env::VarError`,
// found struct `core::num::ParseIntError`) [E0308]
// src/main.rs:63 std::env::var(env).and_then(|v| v.parse::<u32>()).unwrap_or(default)
// ^~~~~~~~~~~~~~~~
// error: aborting due to previous error
// This works by turning the Results into Options.
fn u32_from_env_with_default(env: &str, default: u32) -> u32 {
std::env::var(env).ok()
.and_then(|v| v.parse::<u32>().ok())
.unwrap_or(default)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment