Option xor Means Exactly One Is Some

Option::xor yields Some only when exactly one of the two values is Some, collapsing both-set and neither-set cases to None.

RustForm Validation

Code

rustsnippet
21 lines
fn main() {
    // xor: Some only when exactly one input is Some
    let primary: Option<String> = Some("config.toml".into());
    let fallback: Option<String> = None;
    println!("exactly one: {:?}", primary.xor(fallback));

    let primary: Option<String> = Some("config.toml".into());
    let fallback: Option<String> = Some("config.yaml".into());
    println!("both set: {:?}", primary.xor(fallback));

    let primary: Option<String> = None;
    let fallback: Option<String> = None;
    println!("neither: {:?}", primary.xor(fallback));

    // exactly-one validation: reject configs that set both sources or neither
    let primary: Option<String> = Some("config.toml".into());
    let fallback: Option<String> = None;
    if primary.xor(fallback).is_some() {
        println!("valid: exactly one source configured");
    }
}

How it works

Option xor Means Exactly One Is Some keeps everything in the function main.

Points of care

  • No setup phase: the platform supplies every API the file touches.

Using it

The main signature is written as fn main()

The demo output is labeled (exactly one:, both set:, neither:), so the printed output reads as a trace of the operations performed.

The key statements that remain

let fallback: Option<String> = Some("config.yaml".into());
let primary: Option<String> = Some("config.toml".into());
let fallback: Option<String> = None;

Interactive Tools for This Topic

FAQ

What does Option xor Means Exactly One Is Some print when run?
The script runs standalone; its 4 labeled outputs include `exactly one:`, `both set:`, `neither:`.