Match Float Classes With FpCategory

Classify floats with f64::classify and match FpCategory: NaN, infinite, zero, subnormal, and normal each get an arm.

RustData Integrity

Code

rustsnippet
25 lines
use std::num::FpCategory;

fn describe(value: f64) -> &'static str {
    // match 浮点分类:每个非正常值都有独立分支
    match value.classify() {
        FpCategory::Nan => "not a number",
        FpCategory::Infinite => "infinite",
        FpCategory::Zero => "zero",
        FpCategory::Subnormal => "subnormal",
        FpCategory::Normal => "normal",
    }
}

fn main() {
    let samples = [
        ("42.5", 42.5),
        ("0.0", 0.0),
        ("1e-320", 1e-320), // 小于 f64 最小正规数的边界值
        ("inf", f64::INFINITY),
        ("nan", f64::NAN),
    ];
    for (label, value) in samples {
        println!("{label}: {}", describe(value));
    }
}

What the code does

The working surface is the functions describe and main — everything else is wiring.

Repetition is confined to for (label, value) in samples — the rest of the file is straight-line. Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

Applying it

The entry-point signature is fn describe(value: f64) -> &'static str

Execute the file and main walks through describe, in that order.

Statements that matter

fn describe(value: f64) -> &'static str {
    // match 浮点分类:每个非正常值都有独立分支
    match value.classify() {
        FpCategory::Nan => "not a number",
        FpCategory::Infinite => "infinite",
        FpCategory::Zero => "zero",
        FpCategory::Subnormal => "subnormal",
        FpCategory::Normal => "normal",
    }
}

Interactive Tools for This Topic

FAQ

How do you run Match Float Classes With FpCategory?
The file is self-contained: run it directly, no dependencies to install beforehand.