Match Float Classes With FpCategory
Classify floats with f64::classify and match FpCategory: NaN, infinite, zero, subnormal, and normal each get an arm.
Code
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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.IEEE 754 ConverterConvert decimal floats to and from IEEE 754 single- and double-precision bit patterns in hex and binary.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Match Float Classes With FpCategory?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.