Skip to main content

parse_bool

Function parse_bool 

Source
pub fn parse_bool(raw: Option<&str>) -> Option<bool>
Expand description

Read a value as a boolean, strictly.

TRUE_SPELLINGS and FALSE_SPELLINGS, in any case, after trimming. Anything else — including an absent or blank value — is None, so the caller decides between a default and an error rather than this function guessing.

§Why strict is the default here

The tempting alternative is “anything not false-ish is true”, and it is a trap: ENABLED=disabled, ENABLED=nope and ENABLED=flase all come out true, and the deployment that wrote them looks configured. See parse_bool_lenient for when you nonetheless need that behaviour.

§Examples

use env_reader::parse_bool;

assert_eq!(parse_bool(Some("false")), Some(false));
assert_eq!(parse_bool(Some("OFF")), Some(false));
assert_eq!(parse_bool(Some("  Yes ")), Some(true));
// Unrecognised is not silently true.
assert_eq!(parse_bool(Some("disabled")), None);
assert_eq!(parse_bool(Some("  ")), None);